在WPF中,我想基于组合框选择来动态设置itemsource

时间:2019-01-19 06:15:58

标签: wpf binding itemsource

我的视图中有一个 Slider 和一个 Combobox 。我的ViewModel中有2个属性。基于对组合框的选择,我想将任一属性绑定到滑块的value

 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>

我想将 Slider value绑定到XValueYValue,具体取决于ComboBox的选择

2 个答案:

答案 0 :(得分:1)

您可以将StyleDataTrigger绑定到SelectedItem的{​​{1}}:

ComboBox

答案 1 :(得分:0)

我认为您不能动态更改绑定(至少在XAML中)。但是,您可以执行以下操作:

<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>

Slider现在已绑定到另一个属性(SliderValue)。这是视图模型中添加的属性:

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;
    }
}

这个想法是,当通过SelectedItem更改ComboBox时,Slider会被XValueYValue更新。更改Slider的值时,将根据XValue的选择更新YValueComboBox