如何将在UserControl的组合框中选择的项目传递到主窗口ViewModel

时间:2014-07-02 12:05:16

标签: c# wpf xaml mvvm combobox

我有3个RadioButtons和UserControl MyDataSelector的父视图。 MyDataSelector由ComboBox和其他几个简单控件(CheckBox,Button等)组成。 MyDataSelector的ComboBox应根据父视图中选定的RadioButton填充不同的项目。

我在父视图的XAML中使用MyDataSelector

<controls:MyDataSelector CurrentSelectedValue="{Binding InputElement}" DataContext="{Binding childViewModel}" />

其中

  1. InputElement - 这是父ViewModel中的字符串属性 我想在用户在ComboBox中选择内容时设置。
  2. childViewModel - 这是我的UserControl的ViewModel。
  3. 我使用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);
          }
    ....
    
  4. 以下是MyDataSelector中ComboBox的外观:

    <ComboBox ItemsSource="{Binding AvailableItems}" SelectedItem="{Binding CurrentSelectedValue, ElementName=me}"/>

  5. AvailableItems - 这是一个ObservableCollection<string>,其中填充了不同的元素,具体取决于在父视图中检查了哪个RadioButton。

  6. me这是MyDataSelector UserControl的名称:<UserControl.... x:Name="me">

  7. 任何人都可以帮我找出它无效的原因吗?我看到AvailableItems列表已正确加载,我可以选择ComboBox中的任何项目,但我的父ViewModel中的InputElement属性的getter或setter永远不会被调用,所以我认为绑定有问题: (

1 个答案:

答案 0 :(得分:0)

你试过Two-Way Binding吗?

<controls:MyDataSelector CurrentSelectedValue="{Binding InputElement, Mode=Two-Way}" 
    DataContext="{Binding childViewModel}" />

请参阅MSDN上的Binding.Mode Property页面以获取更多帮助。