我有一个WPF按钮,它当前执行两个我想放入MVVM模式的函数。如果单击时满足条件,则会打开我们动态构建的上下文菜单,否则我们只需执行另一个函数。
private void Button_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
if (MyTest())
{
Button b = sender as Button;
ContextMenu contextMenu = MyContextMenuBuilder();
contextMenu.PlacementTarget = b;
contextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
contextMenu.IsOpen = true;
}
else
{
MyOtherFunction();
}
}
}
我怎么MV-VM这个代码,因为VM不知道放置菜单的按钮,以及菜单本身打开它?
答案 0 :(得分:0)
您可以将MyTest()放入放置在按钮的DataContext中的对象,然后在XAML中定义一个DataTrigger来决定启用的内容。 EG:
public class ButtonAnnotation
{
public object Foo { get; set; }
public bool SatisfiesTest {
get {
... logic for MyTest goes here ...
}
}
}
...
this.TheButtonOrItsParent.DataContext = new ButtonAnnotation();
然后在XAML中:
<DataTrigger Binding="{Binding Path=SatisfiesTest}" Value="True">
<DataTrigger.Setters>
<Setter Property="ContextMenu" Value="{StaticResource TheContextMenu}"/>
</DataTrigger.Setters>
</DataTrigger>