如何在UserControl中向CheckBox添加功能

时间:2019-04-23 18:53:05

标签: c# wpf mvvm

我有一个usercontrol,它是一个显示复选框的下拉菜单。有一个复选框单击事件,它调用SetText函数,该函数根据所选内容(我要保留的内容)设置文本。我还想通过设置自定义功能的命令向用户控件添加功能。例如,当他们选中一个复选框时,我可以调用在viewmodel中设置的函数,并保留SetText函数。

我尝试将Command添加到复选框。以及Command的usecontrol的依赖项属性。另外,在视图模型中可以使用一个简单的功能

-UserControl.xaml

 <ComboBox
    x:Name="CheckableCombo"
    SnapsToDevicePixels="True"
    OverridesDefaultStyle="True"
    ScrollViewer.HorizontalScrollBarVisibility="Auto"
    ScrollViewer.VerticalScrollBarVisibility="Auto"
    ScrollViewer.CanContentScroll="True"
    IsSynchronizedWithCurrentItem="True"
    MinWidth="120"
    MinHeight="20"
    ItemsSource="{Binding ElementName=UserControl, Path=ItemsSource}"
    DataContext="{Binding ElementName=UserControl, Path=DataContext}"
    >
    <ComboBox.ItemTemplate>
        <HierarchicalDataTemplate>
            <CheckBox Content="{Binding Title}"
                      IsChecked="{Binding Path=IsSelected, Mode=TwoWay}"
                      Tag="{RelativeSource FindAncestor, AncestorType={x:Type ComboBox}}"
                      Click="CheckBox_Click"
                      Command="{Binding YourCommand}"

              />
   <i:Interaction.Triggers>
       <i:EventTrigger EventName="SelectionChanged">
         <i:InvokeCommandAction Command="{Binding YourCommand}" />
      </i:EventTrigger>
     </i:Interaction.Triggers>

-UserControl.xaml.cs

    public ICommand YourCommand
    {
        get { return (ICommand)GetValue(YourCommandProperty); }
        set { SetValue(YourCommandProperty, value); }
    }

    // Using a DependencyProperty as the backing store for YourCommand.  This enables animation, styling, binding, etc...
    //public static readonly DependencyProperty YourCommandProperty =
    //    DependencyProperty.Register("YourCommand", typeof(ICommand), typeof(ComboWithCheckboxes), new PropertyMetadata(0));
    public static readonly DependencyProperty YourCommandProperty =
        DependencyProperty.Register("YourCommand", typeof(ICommand), typeof(ComboWithCheckboxes));

    #endregion

    public ComboWithCheckboxes()
    {
        InitializeComponent();
    }

    /// <summary>
    ///Whenever a CheckBox is checked, change the text displayed
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void CheckBox_Click(object sender, RoutedEventArgs e)
    {
        SetText();
    }

    /// <summary>
    ///Set the text property of this control (bound to the ContentPresenter of the ComboBox)
    /// </summary>
    private void SetText()
    {
        this.Text = (this.ItemsSource != null) ?
            this.ItemsSource.ToString() : this.DefaultText;
        // set DefaultText if nothing else selected
        if (string.IsNullOrEmpty(this.Text))
        {
            this.Text = this.DefaultText;
        }
    }

}

-ViewModel.cs

  public ViewModel()
    {
        ViewModelCommand = new DelegateCommand(MethodTest, canExecuteTest);

        itemSource = new ObservableNodeList();
        Node a = new Node("English");
        a.IsSelected = true;
        itemSource.Add(a);

        Node b = new Node("Hebrew");
        b.IsSelected = false;
        itemSource.Add(b);

        Node c = new Node("Swedish");
        c.IsSelected = false;
        itemSource.Add(c);

        Node d = new Node("German");
        d.IsSelected = false;
        itemSource.Add(d);
    }

    private bool canExecuteTest(object obj)
    {
        return true;
    }

    private void MethodTest(object obj)
    {
        System.Windows.MessageBox.Show("Test Method");
    }

我的预期结果是选中或取消选中复选框时能够命中命令功能

1 个答案:

答案 0 :(得分:0)

我简化了您的用户控件,使其更具可读性,并且只专注于有效的外部命令。我修改命令绑定。在列表中,您获得了item的本地数据上下文,但是需要将命令绑定到external-data-context。

 <ComboBox ItemsSource="{Binding ElementName=UserControl, Path=ItemsSource}">
      <ComboBox.ItemTemplate>
          <HierarchicalDataTemplate>
               <CheckBox Content="{Binding .}"
                   Click="CheckBox_Click"
                   Command="{Binding ElementName=UserControl,Path=YourCommand}"> 
                </CheckBox>
          </HierarchicalDataTemplate>
       </ComboBox.ItemTemplate>
 </ComboBox>

在UserControl1.cs中,我得到了:

public ICommand YourCommand
{
    get { return (ICommand)GetValue(YourCommandProperty); }
    set { SetValue(YourCommandProperty, value); }
}

// Using a DependencyProperty as the backing store for YourCommand.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty YourCommandProperty =
            DependencyProperty.Register("YourCommand", typeof(ICommand), typeof(UserControl1), new PropertyMetadata(null));

我进行了测试,它对我有用。