如何将对象绑定到 ComboBox,但在对象更改时更新其他对象

本文关键字:对象 更新 其他 绑定 ComboBox | 更新日期: 2023-09-27 18:32:18

我有一个包含 Zone 对象

public int Block {get;set;}

我还有一个配置对象,其中包含最小和最大Block值,分别为 0 和 2。

我需要显示一个包含有效值范围的组合框,但我需要将所选值绑定到 Block

我最好的方法是什么?

我一直在尝试以下方法:

var blocks = new Dictionary<string, int>();
for (int i = _currentZone.Constraints.Block.Min; i <= _currentZone.Constraints.Block.Max; i++)
{
    blocks.Add("Block " + i, i);
}
var blocksCombo = new ComboBoxControl(blocks, GetCurrentBlockValue());

组合框控件定义为

public ComboBoxControl(Dictionary<string, int> comboItems, int? selectedValue)
{
    InitializeComponent();
    cboItems.ItemsSource = comboItems;
    cboItems.SelectedValue = selectedValue;
}

和 XAML 定义为

<Grid>
    <ComboBox x:Name="cboItems" 
              SelectionChanged="combo_SelectionChanged" 
              Height="25" 
              SelectedValuePath="Value">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=Key}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
</Grid>

当触发combo_SelectionChanged事件时,我手动更新Block值,这并不理想。

我想要的是能够使用字典中的项目设置组合框,但是当我更改所选项目时,该值将绑定到不同的对象 - Block .这可能吗?

如果是这样,我该如何实现?如果没有,有没有比我目前正在做的事情更好的方法

如何将对象绑定到 ComboBox,但在对象更改时更新其他对象

我相信

这就像改变你的 xaml 一样简单......

<ComboBox x:Name="cboItems" 
          SelectionChanged="combo_SelectionChanged" 
          Height="25" 
          SelectedValuePath="Value"
          SelectedItem="{Binding Block}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=Key}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

假设数据上下文设置正确,您可能需要在某个时候将组合框的数据上下文设置为您的 Zone 对象,也许将其与构造函数一起传递......

var blocksCombo = new ComboBoxControl(blocks, GetCurrentBlockValue(), this);
public ComboBoxControl(Dictionary<string, int> comboItems, int? selectedValue, Zone zone)
{
    InitializeComponent();
    cboItems.ItemsSource = comboItems;
    cboItems.SelectedValue = selectedValue;
    cboItems.DataContext = zone;
}

编辑:

另外,我认为Henk是对的,您可能希望将字典更改为ObservableCollection of Block。 (实际上刚刚意识到块只是一个整数,这可能会用作字典)

我希望我理解了一切。您有组合框并想要绑定到一个特定区域?

<ComboBox ItemsSource="{Binding ValidValuesList}" ItemStringFormat="Block {0}" SelectedItem="{Binding MyZone.Block}"/>

这绑定到

public List<int> ValidValuesList
{
    get { return new List<int> { 0, 1, 2 }; }
}

public Zone MyZone { get; set; }

在您的用户控件数据上下文中。