【问题标题】:How to Bind a button in a DataTemplate to a ViewModel?如何将 DataTemplate 中的按钮绑定到 ViewModel?
【发布时间】:2012-04-21 20:16:56
【问题描述】:

我有一个DataTemplate,它放入了ResourceDictionaryDataTemplate 中有一个按钮,我将这个DataTemplate 放入一个窗口中。现在我想将按钮命令绑定到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";
    }

【问题讨论】:

    标签: wpf binding mvvm prism mvvm-light


    【解决方案1】:

    简短的回答是您不需要在代码中执行此操作。

    您将 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();
    }
    

    【讨论】:

    • 感谢 alex,但我不想将 SelectLocationCommand 放在用户类中!!实际上用户是实体类!
    • 有一些解决方案可以在父 ViewModel 中使用该命令,如果您能提供更多关于您的设计的详细信息,我可能会为您提供更好的帮助。当您说 User 实际上是 Entity 类时,您的意思是那是 Model 吗?
    • 感谢alex,它有一个非常简单的解决方案,您只需要为窗口设置一个名称,并在dataTemplate bindig中,将元素名称指定为该名称。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    • 2019-12-27
    • 2020-05-28
    • 1970-01-01
    • 2021-05-21
    • 2012-09-06
    • 1970-01-01
    相关资源
    最近更新 更多