2013-10-17 64 views
0

我有一个类WPF组合框绑定更新多个文本框

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

每一件事情的作品结合

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

是否有可能?

帮助!

+0

你的意思是工具提示?或您的Names类中的'直接'属性?应该提示吗?关闭主题,但我会将您的班级重命名为姓名,公共房产应以大写字母开头。你在使用MVVM吗?在您的ViewModel中实现'INotifyPropertyChanged'可以解决您的问题。 –

+0

我使用INotifyPropertyChanged而不是MVVM – LeBlues

+0

就像@Miiite建议使用MVVM模式会使事情变得更容易。将标签文本绑定到ViewModel中的选定项目。 –

回答

1

我假设你正在使用MVVM。

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

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

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>