如何向用户控件中的复选框添加功能

我有一个用户控件,它是一个显示复选框的下拉菜单。有一个调用 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); }

    }


   

临摹微笑
浏览 91回答 1
1回答

慕容3067478

我简化了您的用户控件,使其更具可读性,并且只关注工作的外部命令。我修改命令的绑定。在列表中,您获得了项目的本地数据上下文,但需要将命令绑定到外部数据上下文。&nbsp;<ComboBox ItemsSource="{Binding ElementName=UserControl, Path=ItemsSource}">&nbsp; &nbsp; &nbsp; <ComboBox.ItemTemplate>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <HierarchicalDataTemplate>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<CheckBox Content="{Binding .}"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Click="CheckBox_Click"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Command="{Binding ElementName=UserControl,Path=YourCommand}">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </CheckBox>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </HierarchicalDataTemplate>&nbsp; &nbsp; &nbsp; &nbsp;</ComboBox.ItemTemplate>&nbsp;</ComboBox>在 UserControl1.cs 中我得到:public ICommand YourCommand{&nbsp; &nbsp; get { return (ICommand)GetValue(YourCommandProperty); }&nbsp; &nbsp; set { SetValue(YourCommandProperty, value); }}// Using a DependencyProperty as the backing store for YourCommand.&nbsp; This enables animation, styling, binding, etc...public static readonly DependencyProperty YourCommandProperty =&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; DependencyProperty.Register("YourCommand", typeof(ICommand), typeof(UserControl1), new PropertyMetadata(null));我测试过,它对我有用。
打开App,查看更多内容
随时随地看视频慕课网APP