簡體   English   中英

WPF組合框綁定以更新多個文本框

[英]WPF Combobox binding to update multiple textbox

我有一堂課

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

一切正常

我想在用戶選擇一個項目時在另一個標簽字段上顯示“提示”。

可能嗎?

救命!

我假設您正在使用MVVM。

您需要在窗口的視圖模型中創建類型為“名稱”的屬性“ CurrentName”,該屬性綁定到ComboBox SelectedItem屬性。 此屬性必須引發NotifyPropertyChanged事件。

然后,將您的標簽字段綁定到此“ CurrentName”屬性。 當組合框上的SelectedIem屬性更改時,您的標簽字段將被更新。

像這樣:您的模型:

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM