![](/img/trans.png)
[英]Get WPF combobox SelectedItem property and assign to a string variable in c# using MVVM pattern
[英]Get WPF combobox SelectedItem property using MVVM pattern
我结合可观察集合到一个combobox
使用MVVM
pattern.I可以成功绑定到combobox
,但现在我正在寻找一种方式来获得SelectedItem
在我看来模型属性(我不能简单地调用它,因为那将是我想象的方式是,必须有某种方法可以在XAML
创建一个绑定,该绑定指向选定的项目,以后可以在视图模型中使用它。我似乎无法弄清楚的是怎么样...
关于如何实现此目标的任何建议?
XAML
<ComboBox SelectedIndex="0" DisplayMemberPath="Text" ItemsSource="{Binding Path=DocumentTypeCmb,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
Grid.Column="1" Grid.Row="4" Margin="0,4,5,5" Height="23"
HorizontalAlignment="Left" Name="cmbDocumentType" VerticalAlignment="Bottom"
Width="230" />
码
//Obesrvable collection property
private ObservableCollection<ListHelper> documentTypeCollection = new ObservableCollection<ListHelper>();
public ObservableCollection<ListHelper> DocumentTypeCmb
{
get
{
return documentTypeCollection;
}
set
{
documentTypeCollection = value;
OnPropertyChanged("DocumentTypeCmb");
}
}
//Extract from the method where i do the binding
documentTypeCollection.Add(new ListHelper { Text = "Item1", IsChecked = false });
documentTypeCollection.Add(new ListHelper { Text = "Item2", IsChecked = false });
documentTypeCollection.Add(new ListHelper { Text = "Item3", IsChecked = false });
DocumentTypeCmb = documentTypeCollection;
//Helper class
public class ListHelper
{
public string Text { get; set; }
public bool IsChecked { get; set; }
}
尝试这个:
public ListHelper MySelectedItem { get; set; }
和XAML:
<ComboBox ItemsSource="{Binding Path=DocumentTypeCmb,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
SelectedItem={Binding MySelectedItem}
/>
您只需要在ViewModel中具有一个公共属性即可获取/设置正确的类型,然后使用绑定将选定的项分配给它。 请注意,SelectedItem是一个依赖属性,因此您可以像这样进行绑定,但是对于列表控件,SelectedItems(请注意复数) 不是依赖属性,因此您不能将其绑定回您的VM-为此,有一个简单的解决方法可以使用而是一种行为。
还要注意,在我的示例中我还没有实现属性更改通知,因此,如果您从VM更改所选项目,则它不会在UI中更新,但这很简单。
当然, ComboBox
具有SelectedItem
属性。 您可以在视图模型中公开一个属性,并在XAML中创建双向绑定。
public ListHelper SelectedDocumentType
{
get { return _selectedDocumenType; }
set
{
_selectedDocumentType = value;
// raise property change notification
}
}
private ListHelper _selectedDocumentType;
…
<ComboBox ItemsSource="{Binding DocumentTypeCmb, Mode=TwoWay}"
SelectedItem="{Binding SelectedDocumentType, Mode=TwoWay}" />
这个怎么样?
SelectedItem={Binding SelectedDocumentType}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.