[英]wpf/mvvm - How to make a ComboBox that sets a specific value from selected item in mvvm
我知道如何使用ComboBox的綁定,但是如何設置一個字符串變量的值
public class Example
{
public string Type { get; set; }
}
使用在其中具有顯示為[=, >, >=, <, <=]
可選項目的ComboBox,然后將其轉換為[=, >, >=, <, <=]
equals, greaterthan...
的適當字符串equals, greaterthan...
例如equals, greaterthan...
如果用戶在ComboBox中選擇=
,則在public string Type { get; set; }
public string Type { get; set; }
public string Type { get; set; }
值equals
它的設置。
我不確定我該怎么做。 在后面寫代碼,查找帶有IF的所選項目並設置所需的字符串? 我真的不知道,也找不到任何類似的例子。 任何幫助都很好,我也在WPF / MVVM Light中做到了
不需要像這樣的東西后面的代碼。 這是使用字典的一種方法:
public class Example
{
public IDictionary<string, string> TypeItems { get; }
= new Dictionary<string, string>
{
// key part is "business" data
// value part is for display only
["equals"] = "=",
["greaterthan"] = ">",
["greaterthanorequals"] = ">=",
["lesserthan"] = "<",
["lesserthanorequals"] = "<=",
};
public string SelectedType { get; set; }
}
在XAML方面:
<ComboBox ItemsSource={Binding TypeItems}
SelectedValue="{Binding SelectedType, Mode=TwoWay}"
SelectedValuePath="Key"
DisplayMemberPath="Value" />
您綁定到的事物的列表可以是任何類型的對象。 您的ViewModel可能如下所示:
class Choice
{
public string Symbol { get; set; }
public string Description { get; set; }
}
class MainViewModel : INotifyPropertyChanged
{
public ObservableCollection<Choice> ComboBoxChoices { get; set; }
public Choice SelectedItem { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public MainViewModel()
{
ComboBoxChoices = new ObservableCollection<Choice>();
ComboBoxChoices.Add(new Choice() { Symbol = "=", Description = "equals" });
ComboBoxChoices.Add(new Choice() { Symbol = ">", Description = "greater than" });
SelectedItem = ComboBoxChoices[0];
}
}
您的XAML可能如下所示:
<ComboBox ItemsSource="{Binding ComboBoxChoices}" DisplayMemberPath="Symbol" SelectedItem="{Binding SelectedItem}" />
當組合框選擇更改時,您可以使用以下內容找到要查找的描述:
mainViewModel.SelectedItem.Description
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.