资源字典 DataTemplate 无法识别 x:Name

时间:2021-06-25 07:00:59

标签: c# wpf xaml

我将此 ResourceDictionary 命名为 Resource1.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:vm="clr-namespace:WpfApp2">
    <DataTemplate DataType="{x:Type vm:MainViewModel}">
        <Button x:Name="SomeButton"  />
    </DataTemplate>
</ResourceDictionary>

目标

我的目标是在不使用 ViewModel 的情况下添加一些代码代码。

我做了什么

我添加了一个名为 Resource1.xaml.cs 的类:

namespace WpfApp2
{
    public partial class Resource1
    {

    }
}

结构现在看起来像这样:

enter image description here

我已将类链接到 xaml。并且还为 Resource1.xaml 中的按钮添加了点击事件:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:vm="clr-namespace:WpfApp2"
                    x:Class="WpfApp2.Resource1">
    <DataTemplate DataType="{x:Type vm:MainViewModel}">
        <Button x:Name="SomeButton" Click="SomeButton_Click" />
    </DataTemplate>
</ResourceDictionary>

然后在 Resource1 类中添加了一个事件处理程序:

public partial class Resource1
{
    private void SomeButton_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        
    }
}

但是当我尝试在类中获取 x:Name="SomeButton" 时,它无法识别它..

enter image description here

问题

是否可以使用资源字典实现我想要做的事情?如果是这样,我应该在哪里更正它以使其正常工作?

1 个答案:

答案 0 :(得分:2)

您不需要通过 x:Name 生成成员。通过 sender 参数获取按钮:

private void SomeButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
    var button = (Button)sender;    
}

请注意,DataTemplate 可能会被多次使用,即可能会创建多个此类按钮。您希望生成的成员引用哪一个?