c# - 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:
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..
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?
解决方案
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?
推荐阅读
- reactjs - Reactjs 待办事项列表 setState
- angular - 重置表格的最佳方式 angular7 表格重置
- vba - 列表框; 如何搜索类型,但自动选择最高值
- javascript - 在“IF-STATEMENT”中成功后显示模式对话框
- ios - iOS 金属。如何对所有色彩作品使用“半”格式?
- flutter - Flutter 必填关键字
- java - 如何使用 JAVA High Level Rest Client 获取索引中存在的文档网总数
- regex - Chrome 开发者工具 - 使用过滤器文本字段来匹配多个请求
- terraform - Terraform - 使用字符串连接/连接变量
- kubernetes - kubeadm init 命令创建的 coredns pod 失败