开发者

Change a WPF context menu on button click event to MVVM

开发者 https://www.devze.com 2023-02-02 09:48 出处:网络
I have a WPF button that currently does two functions that I would like to put into a MVVM pattern. If a condition is met when clicked, it opens a context menu that we build dynamically, otherwise we

I have a WPF button that currently does two functions that I would like to put into a MVVM pattern. If a condition is met when clicked, it opens a context menu that we build dynamically, otherwise we simply execute another function.

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(开发者_运维问答);
       }
    }
}

How do I MV-VM this code since the VM does not have knowledge of the button to place the menu, and the menu itself to open it?


You could put MyTest() into an object that you place within the DataContext of the button, then have a DataTrigger defined in XAML that decides what's enabled. EG:

public class ButtonAnnotation
{
    public object Foo { get; set; }

    public bool SatisfiesTest {
        get {
            ... logic for MyTest goes here ...
        }
    }

}

...
this.TheButtonOrItsParent.DataContext = new ButtonAnnotation();

Then in XAML:

<DataTrigger Binding="{Binding Path=SatisfiesTest}" Value="True">
    <DataTrigger.Setters>
        <Setter Property="ContextMenu" Value="{StaticResource TheContextMenu}"/>
    </DataTrigger.Setters>
</DataTrigger>
0

精彩评论

暂无评论...
验证码 换一张
取 消