
[英]How to pass parameters to usercontrol's viewmodel through window's xaml?
[英]How to pass item that was selected in a combobox of UserControl to the main window ViewModel
我有一个带有3 RadioButtons和UserControl MyDataSelector
的父视图。 MyDataSelector
由ComboBox和其他几个简单的控件(CheckBox,Button等)组成。 MyDataSelector的ComboBox应该填充不同的项目,具体取决于父视图上选择的RadioButton。
我在父视图的XAML中使用MyDataSelector
:
<controls:MyDataSelector CurrentSelectedValue="{Binding InputElement}" DataContext="{Binding childViewModel}" />
哪里
InputElement
这是父ViewModel中的字符串属性,当用户在ComboBox中选择某些内容时,我想设置该属性。 childViewModel
这是我的UserControl的ViewModel。 我使用DependencyProperty定义了CurrentSelectedValue
:
public partial class MyDataSelector: UserControl { public static readonly DependencyProperty CurrentSelectedValueProperty = DependencyProperty.Register("CurrentSelectedValue", typeof(String), typeof(MyDataSelector)); public string CurrentSelectedValue { get {return GetValue(CurrentSelectedValueProperty).ToString(); } set {SetValue(CurrentSelectedValueProperty, value); } ....
这是MyDataSelector中的ComboBox的外观:
<ComboBox ItemsSource="{Binding AvailableItems}" SelectedItem="{Binding CurrentSelectedValue, ElementName=me}"/>
AvailableItems
这是一个ObservableCollection<string>
,其中填充了不同的元素,具体取决于在父视图中检查了哪个RadioButton。
me
是MyDataSelector
UserControl的名称: <UserControl.... x:Name="me">
谁能帮助我找出为什么它不起作用? 我看到AvailableItems
列表已正确加载,并且可以在ComboBox中选择任何项目,但是从未调用我的父ViewModel中的InputElement
属性的getter或setter,因此绑定有问题,我相信:(
您是否尝试过Two-Way Binding
?
<controls:MyDataSelector CurrentSelectedValue="{Binding InputElement, Mode=Two-Way}"
DataContext="{Binding childViewModel}" />
请参阅MSDN上的Binding.Mode属性页面以获取与此有关的更多帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.