C# 如何将一个对象绑定到一个组合框,但在它更改时更新另一个对象?

C# 如何将一个对象绑定到一个组合框,但在它更改时更新另一个对象?,c#,wpf,xaml,binding,combobox,C#,Wpf,Xaml,Binding,Combobox,我有一个区域对象,其中包含 public int Block {get;set;} 我还有一个配置对象,其中包含最小值和最大值块值,分别为0和2 我需要显示一个包含有效值范围的组合框,但我需要将所选值绑定到块 对我来说最好的方法是什么 我一直在尝试以下方法: var blocks = new Dictionary<string, int>(); for (int i = _currentZone.Constraints.Block.Min; i <= _currentZone

我有一个
区域
对象,其中包含

public int Block {get;set;}
我还有一个配置对象,其中包含最小值和最大值
值,分别为0和2

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

对我来说最好的方法是什么

我一直在尝试以下方法:

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());
var blocks=newdictionary();

对于(int i=_currentZone.Constraints.Block.Min;i我相信这就像将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>

假设数据上下文设置正确,您可能需要在某个时候将combobox的datacontext设置为区域对象,或者将其与构造函数一起传递

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;
}
var blocksCombo=new ComboBoxControl(blocks,GetCurrentBlockValue(),this);
公共ComboBox控件(字典comboItems、int?selectedValue、Zone)
{
初始化组件();
cboItems.ItemsSource=组合项;
cboItems.SelectedValue=SelectedValue;
cboItems.DataContext=区域;
}
编辑:


此外,我认为Henk是对的,您可能希望将字典改为块的ObservableCollection(实际上刚刚实现的块只是一个int,这可能会用作字典)

我希望我理解的一切都是正确的。您有组合框,想绑定到一个特定区域

<ComboBox ItemsSource="{Binding ValidValuesList}" ItemStringFormat="Block {0}" SelectedItem="{Binding MyZone.Block}"/>
在usercontrols数据上下文中

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