我有一个 DataTemplate
已放入 ResourceDictionary
,并且DataTemplate
中有一个按钮我把这个 DataTemplate
在一个窗口中。现在我想将按钮命令绑定(bind)到 windowViewModel
的属性。 ,我怎样才能做到这一点?
这是代码:
<DataTemplate DataType="{x:Type types:User}" x:Key="UserTemp">
<Grid >
<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ????}, AncestorLevel=1}, Path=SelectLocationCommand}" />
</Grid>
</DataTemplate>
在 Window.xaml 中
<ContentControl x:Name="UserTemp" />
在 WindowViewModel 中:
public ICommand SelectLocationCommand
{
get {return new RelayCommand(selectLocationCommand); }
}
void selectLocationCommand()
{
_welcomeTitle = "AA";
}
最佳答案
简短的回答是您不需要在代码中执行此操作。
您将 DataTemplate 定义为“用户”对象的模板。这意味着这就是用户对象应该在 UI 中显示的方式。因此,为了使用您的 DataTemplate,您应该在 WindowViewModel 中有一个“用户”实例。这意味着 SelectLocationCommand 应该在 User 对象中,而不是在 WindowViewModel 中。
说了这么多,你的代码应该是这样的:
在 Window.xaml 中
<ContentControl Content="{Binding User}" ContentTemplate="{StaticResource UserTemp}" />
在 WindowViewModel 中
public User User {get;set}
在用户中
public ICommand SelectLocationCommand
{
get {return new RelayCommand(selectLocationCommand); }
}
void selectLocationCommand()
{
_welcomeTitle = "AA";
}
此外,请确保 Window.xaml 的 DataContext 是 WindowViewModel。有许多更好的方法可以做到这一点,但最简单的方法是:
在 Window.xaml.cs 中
public MainWindow()
{
InitializeComponent();
this.DataContext = new WindowViewModel();
}
关于wpf - 如何将 DataTemplate 中的按钮绑定(bind)到 ViewModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10073531/