简体   繁体   English

C#/ WPF:将ComboBox绑定到两个元素吗?

[英]C#/WPF: Bind ComboBox to two Elements?

I've following objects 我关注的对象

public int PersonAge { get; set; }
public List<PersonGroup> PersonList { get; set; }

public class PersonGroup()
{
    public string Name { get; set; }
    public string DefaultAge { get; set; }
}

My ComboBox is bound to PersonList, while I also have a TextBox which is bound to PersonAge. 我的ComboBox绑定到PersonList,而我也有一个TextBox绑定到PersonAge。 If a user enters the number '20' into the TextBox (PersonAge), I want to select the according PersonGroup in the ComboBox, and if a User selects the PersonGroup-Item "Test1" from the ComboBox, I want the TextBox to display 10 in the TextBox (because PersonList[1] would be for example Name = "Test1"; DefaultAge = 10;) 如果用户在文本框(PersonAge)中输入数字'20',我想在组合框中选择相应的PersonGroup,并且如果用户从组合框中选择PersonGroup-Item“ Test1”,我希望文本框显示10在TextBox中(因为PersonList [1]例如是Name =“ Test1”; DefaultAge = 10;)

Any ideas how to solve this via DataBinding? 任何想法如何通过DataBinding解决此问题?

Thanks a lot. 非常感谢。

Cheers, Joseph 干杯,约瑟夫

Off the top of my head, you could try using the SelectedValue and SelectedValuePath properties on ComboBox: 在我头顶上,您可以尝试使用ComboBox上的SelectedValue和SelectedValuePath属性:

<ComboBox x:Name="ComboBox" SelectedValuePath="DefaultAge" SelectedValue="{Binding PersonAge}"/>
<TextBox Text="{Binding ElementName=ComboBox, Path=SelectedValue}"/>

edit1: i think the textbox can bind to PersonAge instead, makes for cleaner code imo....not sure, unfortunately i cant test it at the moment. edit1:我认为文本框可以绑定到PersonAge,从而使代码更简洁imo ....不确定,不幸的是我目前无法对其进行测试。

You can expose ListCollectionView , instead of raw List. 您可以公开ListCollectionView ,而不是原始List。 Set up Filter function. 设置过滤器功能。 And whenether PersonAge is updated you call Refresh() method from your view. 当PersonAge进行更新时,您可以从视图中调用Refresh()方法。 As for another part - you can always bind to current item in the collection view. 至于另一部分-您始终可以在集合视图中绑定到当前项目。 Eg: 例如:

<TextBox Text="{Binding PersonList/DefaultAge}"/>

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM