我多次使用样式来扩展控件的功能。例如,如果您有一个控件来从Person收集数据,并且您想将它用于继承自Person但具有一些其他字段的其他类Student,则可以将这些字段添加到默认样式并将控件绑定到Student实例
但是现在我需要添加一个按钮来加载文件并将路径存储在类的属性中,该属性是控件的DataContext
。这就是我需要为按钮行为添加代码的原因。
我想知道是否可以将C#代码添加到样式中定义的控件中。我想答案是肯定的,但我不是专家。
感谢您的帮助。
答案 0 :(得分:0)
实际上附加行为是此问题的解决方案。使用此技术,您可以将代码注入您无法修改的控件。
在这种情况下,我在一个样式中有一个按钮,我想将一个事件处理程序附加到Click Event
。第一种方法是将行为创建为Dependency Property
,稍后我们需要在Dependency Property
中设置此Button
。
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.
}
}
}
现在在Button
<Button>
<Button.Style>
<Style>
<Setter Property="local:OpenFileDialogOnClickBehavior.OpenFileDialogOnClick" Value="True" />
</Style>
</Button.Style>
</Button>
<!-- Code of the style... -->
我使用 benPearce 在评论中提供的链接来创建此答案。那里有更详细的描述。