首页 > 解决方案 > 在 WPF 中,我想根据组合框选择动态设置 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 的选择

标签: wpfbindingitemsource

解决方案


您可以使用 aStyle与 aDataTrigger绑定到SelectedItemComboBox

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

推荐阅读