因为你可能想在一个风格资源的事件处理程序,我建议背后的创建代码ResourceDictionary中。只需在Visual Studio中创建用户控件和替换里面的代码 - 你将有两个*的.xaml和* .xaml.cs文件很好地嵌套。为了在整个应用程序申请样式DataGrid中,包括他们在App.xaml中应用程序的资源:
<Application.Resources>
<ResourceDictionary Source="MyStyles.xaml"/>
</Application.Resources>
代码在MyStyles.xaml文件:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="Example.MyStyles"
xmlns:vmcc="clr-namespace:Example">
<Style TargetType="{x:Type DataGridCell}" x:Key="DataGrid.DataGridCellStyle">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridCell_PreviewMouseLeftButtonDown"></EventSetter>
<Style.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter Property="BorderBrush" Value="White" />
<Setter Property="BorderThickness" Value="2" />
</Trigger>
</Style.Triggers>
</Style>
<Style TargetType="{x:Type vmcc:LOVComboBox}" x:Key="DataGrid.LOVComboBoxStyle">
<EventSetter Event="Loaded" Handler="UIElement_GotFocus"></EventSetter>
</Style>
<Style TargetType="{x:Type TextBox}" x:Key="DataGrid.TextBoxStyle">
<EventSetter Event="Loaded" Handler="UIElement_GotFocus"></EventSetter>
</Style>
<Style TargetType="{x:Type DataGrid}">
<Style.Resources>
<Style TargetType="DataGridCell" BasedOn="{StaticResource DataGrid.DataGridCellStyle}" />
<Style TargetType="vmcc:LOVComboBox" BasedOn="{StaticResource DataGrid.LOVComboBoxStyle}" />
<Style TargetType="TextBox" BasedOn="{StaticResource DataGrid.TextBoxStyle}" />
</Style.Resources>
</Style>
</ResourceDictionary>
我们希望有TextBox,仅在DataGrid内部应用LOVComboBox样式 - 这就是为什么它们的样式包含在DataGrid样式的Style.Resources中的原因。我试图把那里的风格,从你的代码拷贝(不带X:主要属性),但我得到了一个错误: 事件“的PreviewMouseLeftButtonDown”不能在样式一个目标标签中指定。改用EventSetter。。这就是为什么我提取他们与键的资源和在DataGrid的风格Style.Resources使用衍生样式(如建议here)。
代码在MyStyles.xaml.cs文件:
public partial class MyStyles
{
private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//your code here
}
private void UIElement_GotFocus(object sender, RoutedEventArgs e)
{
//your code here
}
}
工作完美,感谢您使用代码的完整的解释! – Louro