使用 MVVM 将按钮名称从 XAML 传递到 ViewModel
本文关键字:XAML ViewModel MVVM 按钮 使用 | 更新日期: 2023-09-27 18:35:20
在我的XAML
中,我定义了一个按钮:
<DataTemplate x:Key="ItemTemplate">
<WrapPanel Orientation="Vertical" Width="Auto">
<Button Width="200" Height="300" Click="SelectMovie_Click" >
<Button.Template>
<ControlTemplate >
<Image Source="{Binding image}"/>
</ControlTemplate>
</Button.Template>
<i:Interaction.Behaviors>
<local:UniqueNameBehavior ID="{Binding id}"/>
</i:Interaction.Behaviors>
</Button>
<TextBlock Text="{Binding title}" HorizontalAlignment="Center"/>
</WrapPanel>
</DataTemplate>
我使用Behaviour
为我的按钮动态分配名称。
public class UniqueNameBehavior : Behavior<FrameworkElement>
{
public UniqueNameBehavior() : base() { }
public String ID
{
get { return (String)this.GetValue(IDProperty); }
set { this.SetValue(IDProperty, value); }
}
protected override void OnAttached()
{
base.OnAttached();
//Assign unique name to the associated element
AssociatedObject.Name = "movie" + ID;
}
public static readonly DependencyProperty IDProperty = DependencyProperty.Register(
"ID", typeof(String),
typeof(UniqueNameBehavior));
}
单击此按钮时,我想将此Name
传递给我的ViewModel
。
这是我的Behind-Code
private void SelectMovie_Click(object sender, RoutedEventArgs e)
{
// _moviePanelVM is an instance of my ViewModel
_moviePanelVM.GetSelectedMovieDetails();
}
所以我知道我可以在这里检索按钮名称并将其传递给ViewModel
但我觉得如果使用MVVM
模型,这可能不是正确的方法。
谁能建议我如何以正确的方式实现这一目标?
谢谢你的帮助。
您可以在 ViewModel 中添加命令: 例如,此处的命令部分可能会有所帮助: 使用 Prism Library 5.0 for WPF 实现 MVVM 模式。
并在 Prism 库的帮助下添加一个参数化的命令,并作为参数提交按钮的名称(互联网上充满了帮助)。并将命令绑定到您的按钮。
在 XAML 文件中使用命令参数。这是简单的 sintax 传递带有按钮"CommandParameter={Binding senderObject}"的对象,在按钮标签的末尾添加此内容。
在
private void SelectMovie_Click(object sender, RoutedEventArgs e)
{
String buttonId = sender as String;
// _moviePanelVM is an instance of my ViewModel
_moviePanelVM.GetSelectedMovieDetails();
}