Reputation: 55
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
Upvotes: 0
Views: 845
Reputation: 169150
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>
Upvotes: 1
Reputation: 2497
I don't think you can change the binding dynamically (in XAML, at least). However, you can do the following:
<StackPanel>
<ComboBox SelectedIndex="{Binding SelectedIndex}" Margin="2" Width="100">
<ComboBoxItem Tag="X">X</ComboBoxItem>
<ComboBoxItem Tag="Y">Y</ComboBoxItem>
</ComboBox>
<Slider Value="{Binding SliderValue}"></Slider>
</StackPanel>
The Slider
is now bound to another property (SliderValue
). Here are the added properties in your view model:
private int _selectedIndex;
public int SelectedIndex
{
get { return _selectedIndex; }
set
{
_selectedIndex = value;
NotifyPropertyChanged();
if (SelectedIndex == 0)
SliderValue = XValue;
else if (SelectedIndex == 1)
SliderValue = YValue;
}
}
private int _sliderValue;
public int SliderValue
{
get { return _sliderValue; }
set
{
_sliderValue = value;
NotifyPropertyChanged();
if (SelectedIndex == 0)
XValue = SliderValue;
else if (SelectedIndex == 1)
YValue = SliderValue;
}
}
The idea is that when the SelectedItem
is changed via the ComboBox
, the Slider
is updated with either XValue
or YValue
. When the Slider
value is changed, the XValue
or YValue
is updated depending on the ComboBox
selection.
Upvotes: 0