Search code examples
c#wpfmvvmbindingischecked

Bind IsChecked to boolean of struct wpf


I have the following struct:

public struct StreamContainer
{
    public string Name { get; set; }
    public bool IsVisible { get; set; }
    public Canvas Canvas { get; set; }
}

The following private member:

private ObservableCollection <StreamContainer> m_listOfStreams = new ObservableCollection<StreamContainer>();

An the following property:

public ObservableCollection<StreamContainer> ListOfStreams
{
    get { return m_listOfStreams; }
    set
    {
        m_listOfStreams = value;
        OnPropertyChanged();
    }
}

In my 'Xaml', I have this:

<MenuItem x:Name="StreamsMenu" Header="Streams" Foreground="DarkRed"  Focusable="False">
   <MenuItem x:Name="ColorStream" Header="Color" IsCheckable="True" IsChecked="True" Foreground="DarkRed" Click="SelectStream_OnClick"/>
   <MenuItem x:Name="GrayStream" Header="Depth" IsCheckable="True" Foreground="DarkRed" Click="SelectStream_OnClick"/>
</MenuItem>

Is it possible to bind each of the MenuItems IsChecked property (ColorStream and GrayStream) to their matching IsVisible property? Meaning, for example, that the IsChecked property of the ColorStream will be binded to the 'IsVisible' property of first item in the ObservableCollection.


Solution

  • If you know that there are always at least two items in the source collection and that the DataContext of the parent Menu is set to an instance of the class where the ListOfStreams property is defined you could do this:

    <Menu>
        <MenuItem x:Name="StreamsMenu" Header="Streams" Foreground="DarkRed"  Focusable="False">
            <MenuItem x:Name="ColorStream" Header="Color" IsCheckable="True"
                              IsChecked="{Binding Path=DataContext.ListOfStreams[0].IsVisible, RelativeSource={RelativeSource AncestorType=Menu}}" 
                              Foreground="DarkRed" />
            <MenuItem x:Name="GrayStream" Header="Depth" IsCheckable="True" 
                              IsChecked="{Binding Path=DataContext.ListOfStreams[1].IsVisible, RelativeSource={RelativeSource AncestorType=Menu}}" 
                              Foreground="DarkRed"/>
        </MenuItem>
    </Menu>