0

我有课

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" />

每件事都有效

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

可能吗?

帮助!

4

2 回答 2

1

我假设您正在使用 MVVM。

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

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

于 2013-10-17T16:16:20.103 回答
0

像这样:你的模型:

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

您的视图模型:

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>

于 2013-10-17T16:40:45.990 回答