如何访问 Window.Resources 的 ControlTemplate 的内部元素?
这个问题已经在各地被问过很多次了,但解决方案要么是不好的做法并且不建议,要么对问题不通用。也许这个线程可以解决这个问题!
我的窗口中有 ControlTemplate:
<Window>
<Window.Resources>
<ControlTemplate x:Key="buttonControl" TargetType="{x:Type Control}">
<Grid Name="grdButtons" FlowDirection="LeftToRight" Height="35" HorizontalAlignment="Right">
<Button Name="btnOk" Content="Ok" Width="75" Margin="10,10,255,0" HorizontalAlignment="Right" IsDefault="True" Click="btnOk_Click" />
<Button Name="btnCancel" Content="Cancel" Width="75" HorizontalAlignment="Right" Margin="10,10,175,0" IsCancel="True" Click="btnCancel_Click"/>
<Button Name="btnApply" Content="Apply" Width="75" HorizontalAlignment="Right" Margin="10,10,95,0" Click="btnApply_Click" />
<Button Name="btnDeleteRule" Content="Delete" Width="75" HorizontalAlignment="Right" Margin="10,10,15,0" Click="btnDeleteRule_Click" />
</Grid>
</ControlTemplate>
</Window.Resources>...
从代码隐藏中,我需要根据我在代码中设置的一些操作来启用或禁用此按钮。如何从代码隐藏中正确访问按钮 btnDeleteRule?我尝试过使用 FindName() 但总是得到 null。
This question has been asked many times all over the place, but the solutions are either bad practice and not advised, or not generic to the problem. Maybe this thread can fix that!
I have ControlTemplate within my Window:
<Window>
<Window.Resources>
<ControlTemplate x:Key="buttonControl" TargetType="{x:Type Control}">
<Grid Name="grdButtons" FlowDirection="LeftToRight" Height="35" HorizontalAlignment="Right">
<Button Name="btnOk" Content="Ok" Width="75" Margin="10,10,255,0" HorizontalAlignment="Right" IsDefault="True" Click="btnOk_Click" />
<Button Name="btnCancel" Content="Cancel" Width="75" HorizontalAlignment="Right" Margin="10,10,175,0" IsCancel="True" Click="btnCancel_Click"/>
<Button Name="btnApply" Content="Apply" Width="75" HorizontalAlignment="Right" Margin="10,10,95,0" Click="btnApply_Click" />
<Button Name="btnDeleteRule" Content="Delete" Width="75" HorizontalAlignment="Right" Margin="10,10,15,0" Click="btnDeleteRule_Click" />
</Grid>
</ControlTemplate>
</Window.Resources>...
From codebehind, I need to enable or disable this button based on some actions I set up in code. How can I properly access the button btnDeleteRule from code behind? I have tried using FindName() but always get null.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
答案仍然是:
IsEnabled
绑定到属性。如果您想忽略“不要这样做”,您需要使用
FindName
在模板上,而不是控件上。The answer to that is still:
IsEnabled
to a property.And if you want to disregard the "don't do it" you need to use
FindName
on the template, not the control.