【问题标题】:How to add function to CheckBox in a UserControl如何在 UserControl 中向 CheckBox 添加功能
【发布时间】:2019-04-24 16:56:11
【问题描述】:

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

我尝试在复选框中添加一个命令。以及命令的 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");
    }

我的预期结果是能够在选择或取消选择复选框时点击命令功能

【问题讨论】:

    标签: c# wpf mvvm


    【解决方案1】:

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

     <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));
    

    我测试过,它对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-14
      • 2015-09-27
      • 1970-01-01
      • 2017-08-24
      • 2015-06-15
      • 2020-11-22
      相关资源
      最近更新 更多