wpfbindingitemsource

In WPF, I want to dynamically set the itemsource based on combo box selection


I have a Slider and a Combobox in my view. I have 2 properties in my ViewModel. Based on the selection of the combobox, I want to bind any one of the property to the value of the slider.

 private int _xValue;

    public int XValue
    {
        get { return _xValue; }
        set
        {
            _xValue = value;
            NotifyPropertyChanged();
        }
    }

    private int _yValue;

    public int YValue
    {
        get { return _yValue; }
        set
        {
            _yValue = value;
            NotifyPropertyChanged();
        }
    }

 <StackPanel>
     <ComboBox SelectedIndex="0" Margin="2" Width="100">
        <ComboBoxItem Tag="X">X</ComboBoxItem>
        <ComboBoxItem Tag="Y">Y</ComboBoxItem>
    </ComboBox>

    <Slider Value="{Binding XValue}"></Slider>
</StackPanel>

I want to bind the Slider value to XValue or YValue depending on the selection of the ComboBox


Solution

  • You could use a Style with a DataTrigger that binds to the SelectedItem of the ComboBox:

    <ComboBox x:Name="cmb" SelectedIndex="0" Margin="2" Width="100">
        <ComboBoxItem Tag="X">X</ComboBoxItem>
        <ComboBoxItem Tag="Y">Y</ComboBoxItem>
    </ComboBox>
    
    <Slider>
        <Slider.Style>
            <Style TargetType="Slider">
                <Setter Property="Value" Value="{Binding XValue}" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding SelectedItem.Tag, ElementName=cmb}" Value="Y">
                        <Setter Property="Value" Value="{Binding YValue}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Slider.Style>
    </Slider>