首页 > 解决方案 > Resource Dictionary DataTemplate does not recognise the x:Name

问题描述

I have this ResourceDictionary named as 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>

Goal

I am aiming to add some code code behind without using the ViewModel.

What I did

I added a class called Resource1.xaml.cs:

namespace WpfApp2
{
    public partial class Resource1
    {

    }
}

And the structure now looks like so:

enter image description here

I have linked the class to the xaml. And also added a click event for the button in the 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>

Which then added me an event handler in the Resource1 class:

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

But when I try getting the x:Name="SomeButton" in the class, it does not recognise it..

enter image description here

Question

Is it possible to achieve what I am trying to do using Resource Dictionary? If so, where do I correct it to make it work?

标签: c#wpfxaml

解决方案


You don't need to generate a member by x:Name. Get the Button via the sender argument:

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

Be aware that the DataTemplate may be used multiple times, i.e. multiple such Buttons may be created. Which one would you want to reference by the generated member?


推荐阅读