我仍在努力修改我现有的 WPF 应用程序,使其与 MVVM 方法“兼容”。我已经非常接近了,但我不确定如何解决剩下的几个障碍之一。
我有一个 GUI 元素(当前是一个按钮,虽然它可能是一个标签),当鼠标进入它时,它会触发 MouseEnter 事件,这会在代码隐藏中创建一个弹出窗口。弹出窗口由一个带有几个按钮的简单堆栈面板布局组成。当前,每个按钮的 Click 事件都分配给同一个事件处理程序,除了我将 Tag 属性更改为执行一个简单(俗气的)命令参数。我正在与在 MVVM 中执行此操作的“正确”方式作斗争,因为我现在这样做的方式非常丑陋。
为了解决这个问题,我认为这是我应该前进的方向,但如果你能提供任何额外的意见,我将不胜感激。 :)
<Popup x:Key="MyPopup" StaysOpen="False" Placement="Right">
<Border Background="White" BorderBrush="Black" Padding="5" BorderThickness="2" CornerRadius="5">
<StackPanel Orientation="Vertical">
<Button Command="{Binding MyCommand}" CommandParameter="5">5</Button>
<Button Command="{Binding MyCommand}" CommandParameter="10">10</Button>
<Button Command="{Binding MyCommand}" CommandParameter="15">15</Button>
<Button Command="{Binding MyCommand}" CommandParameter="20">20</Button>
</StackPanel>
</Border>
</Popup>
<Button.Triggers>
<Trigger Property="Button.IsMouseOver" Value="True">
<Setter TargetName="MyPopup" Property="IsOpen" Value="True" />
</Trigger>
</Button.Triggers>
我认为#1还可以,但我在#2中挣扎。这是解决问题的正确方法吗?如果是这样,将 Popup 的 IsOpen 属性设置为 True 的正确 XAML 语法是什么?我找不到这方面的例子。
如果我的整个想法有缺陷,我很想听听我的其他选择是什么。谢谢!
最佳答案
这是我要做的,首先我将我的可重用部分分成资源,并使用 ContentControls
引用它们在 XAML 中。这适用于 Popup
以及 Button
.但是我不想限制自己只有一个按钮,所以我将使用 ContentControl
也为此:
弹出模板:
<ControlTemplate x:Key="PopupTemplate">
<Border
Background="White"
BorderBrush="Black"
Padding="5"
BorderThickness="2"
CornerRadius="5">
<StackPanel Orientation="Vertical">
<Button Command="{Binding MyCommand}"
CommandParameter="5">5</Button>
<Button Command="{Binding MyCommand}"
CommandParameter="10">10</Button>
<Button Command="{Binding MyCommand}"
CommandParameter="15">15</Button>
<Button Command="{Binding MyCommand}"
CommandParameter="20">20</Button>
</StackPanel>
</Border>
</ControlTemplate>
ContentControl
模板:<ControlTemplate x:Key="MyControlTemplate" TargetType="ContentControl">
<Grid Name="MyControl">
<ContentPresenter Content="{TemplateBinding Content}"/>
<Popup Name="MyPopup" StaysOpen="True" Placement="Bottom">
<ContentControl Template="{StaticResource PopupTemplate}"/>
</Popup>
</Grid>
<ControlTemplate.Triggers>
<Trigger SourceName="MyControl"
Property="UIElement.IsMouseOver"
Value="True">
<Setter TargetName="MyPopup"
Property="Popup.IsOpen"
Value="True"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
现在在主窗口 XAML 中,我将创建以下内容:
<ContentControl Template="{StaticResource MyControlTemplate}">
<Button Content="Test"/>
</ContentControl>
如果您有任何问题,我很乐意为您解答。
关于wpf - MVVM + WPF + Popup = 无能为力,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1997909/