C# 是否可以向样式中添加的控件添加代码?
我已经多次使用样式来扩展控件的功能。例如,如果您有一个从Person收集数据的控件,并且您希望将其用于从Person继承但具有一些附加字段的其他类Student,则可以将这些字段添加到默认样式,并将该控件绑定到Student实例 但是现在我需要添加一个按钮来加载文件并将路径存储在类的属性中,该类是控件的C# 是否可以向样式中添加的控件添加代码?,c#,wpf,xaml,C#,Wpf,Xaml,我已经多次使用样式来扩展控件的功能。例如,如果您有一个从Person收集数据的控件,并且您希望将其用于从Person继承但具有一些附加字段的其他类Student,则可以将这些字段添加到默认样式,并将该控件绑定到Student实例 但是现在我需要添加一个按钮来加载文件并将路径存储在类的属性中,该类是控件的DataContext。这就是为什么我需要为按钮行为添加代码 我想知道是否可以将C#代码添加到以样式定义的控件中。我想答案是否定的,但我不是专家 谢谢你的帮助。实际上,附加行为是这个问题的解决方案
DataContext
。这就是为什么我需要为按钮行为添加代码
我想知道是否可以将C#代码添加到以样式定义的控件中。我想答案是否定的,但我不是专家
谢谢你的帮助。实际上,附加行为是这个问题的解决方案。使用此技术,您可以将代码注入无法修改的控件 在本例中,样式中有一个按钮,我希望将事件处理程序附加到
单击事件
。第一部分是将行为创建为依赖属性
,之后我们需要在按钮中设置此依赖属性
class OpenFileDialogOnClickBehavior
{
public static bool GetOpenFileDialogOnClick(Button button)
{
return (bool)button.GetValue(OpenFileDialogOnClickProperty);
}
public static void SetOpenFileDialogOnClick(Button button, bool value)
{
button.SetValue(OpenFileDialogOnClickProperty, value);
}
public static readonly DependencyProperty OpenFileDialogOnClickProperty =
DependencyProperty.RegisterAttached(
"OpenFileDialogOnClick",
typeof(bool),
typeof(OpenFileDialogOnClickBehavior),
new UIPropertyMetadata(false, OnOpenFileDialogOnClick));
static void OnOpenFileDialogOnClick(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
Button button = depObj as Button;
if (button == null)
return;
if (e.NewValue is bool == false)
return;
if ((bool)e.NewValue)
button.Click += OnClick;
else
button.Click -= OnClick;
}
static void OnClick(object sender, RoutedEventArgs e)
{
// Only react to the Click event raised by the Button. Ignore all ancestors
// who are merely reporting that a descendant's Click fired.
if (!ReferenceEquals(sender, e.OriginalSource))
return;
Button button = e.OriginalSource as Button;
if (button != null)
{
// Open File Dialog or any action to react to the Click Event.
}
}
}
现在在按钮中设置属性
我使用了benPearce在评论中提供的链接来创建这个答案。这里有一个更详细的描述。我想你可以通过一个附加的行为来实现这一点:@benPearce我正在读这篇文章。听起来很有希望。谢谢你的回复。
<Button>
<Button.Style>
<Style>
<Setter Property="local:OpenFileDialogOnClickBehavior.OpenFileDialogOnClick" Value="True" />
</Style>
</Button.Style>
</Button>
<!-- Code of the style... -->