WPF Combobox绑定更新多个文本框

时间:2013-10-17 15:56:59

标签: c# wpf data-binding

我有一个班级

class Names {
public int id get; set;};
public string name {get ; set};
public string til {set{
if (this.name == "me"){
return "This is me";
}
}

我有一个列表(ListNames),其中包含添加到其中的名称并与组合框绑定

<ComboBox  SelectedValue="{Binding Path=id, Mode=TwoWay,
 UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding
 ListNames}" DisplayMemberPath="name" SelectedValuePath="id" />

每件事都有效

我想在用户选择项目时在另一个标签字段上显示“提示”。

有可能吗?

帮助!

2 个答案:

答案 0 :(得分:1)

我假设您正在使用MVVM。

您需要在窗口的viewmodel中创建一个类型为“Names”的属性“CurrentName”,绑定到ComboBox SelectedItem属性。 此属性必须引发NotifyPropertyChanged事件。

然后,将您的标签字段绑定到此“CurrentName”属性。 当SelectedIem属性在组合框上发生变化时,您的标签字段将会更新。

答案 1 :(得分:0)

这样的事情: 你的型号:

public class Names 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Tip {
        get
        {
            return Name == "me" ? "this is me" : "";
        }
    }
}

您的ViewModel:

public class ViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Names> _namesList;
    private Names _selectedName;

    public ViewModel()
    {
        NamesList = new ObservableCollection<Names>(new List<Names>
            {
                new Names() {Id = 1, Name = "John"},
                new Names() {Id = 2, Name = "Mary"}
            });
    }

    public ObservableCollection<Names> NamesList
    {
        get { return _namesList; }
        set
        {
            _namesList = value;
            OnPropertyChanged();
        }
    }

    public Names SelectedName
    {
        get { return _selectedName; }
        set
        {
            _selectedName = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

最后你的观点:

<Window x:Class="Combo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Combo="clr-namespace:Combo"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <Combo:ViewModel/>
</Window.DataContext>
<StackPanel>
    <ComboBox ItemsSource="{Binding Path=NamesList}" DisplayMemberPath="Name" 
              SelectedValue="{Binding Path=SelectedName}"/>
    <Label Content="{Binding Path=SelectedName.Name}"/>
</StackPanel>