【发布时间】: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");
}
我的预期结果是能够在选择或取消选择复选框时点击命令功能
【问题讨论】: