简体   繁体   中英

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. 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;)

Any ideas how to solve this via DataBinding?

Thanks a lot.

Cheers, Joseph

Off the top of my head, you could try using the SelectedValue and SelectedValuePath properties on ComboBox:

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

You can expose ListCollectionView , instead of raw List. Set up Filter function. And whenether PersonAge is updated you call Refresh() method from your view. As for another part - you can always bind to current item in the collection view. Eg:

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

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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