[英]How to style auto-generated elements in xaml
我使用此扩展这个工具包,它自动添加一个TextBox
到每个数据网格列的顶部,用于从下面的代码滤波。
<DataGrid ColumnHeaderStyle="{StaticResource {ComponentResourceKey
TypeInTargetAssembly={x:Type filter:DataGridHeaderFilterControl},
ResourceId=DataGridHeaderFilterControlStyle}}" >
但是,添加的列标题和文本框的样式与我想要的样式不同。
因此,我可以执行此操作以设置列标题的样式,但不会更改文本框。
<Style x:Key="FilterHeader"
BasedOn="{StaticResource {ComponentResourceKey TypeInTargetAssembly={x:Type filter:DataGridHeaderFilterControl},
ResourceId=DataGridHeaderFilterControlStyle}}"
TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Foreground" Value="Blue" />
</Style>
...
<DataGrid ColumnHeaderStyle="{DynamicResource FilterHeader}">
我尝试将其放在Window.Resources
以查看它是否对文本框有影响。 它更改了我的其他文本框,对扩展创建的文本框没有任何影响。
<Style TargetType="TextBox">
<Setter Property="Foreground" Value="Blue" />
</Style>
但是没有骰子。 我发现唯一可行的方法是:
public void DataGrid_OnLoad(object sender, RoutedEventArgs e)
{
IEnumerable<System.Windows.Controls.TextBox> collection =
FindVisualChildren<System.Windows.Controls.TextBox>(TitleBar);
foreach (System.Windows.Controls.TextBox tb in collection)
{
tb.Foreground = Brushes.Blue;
}
}
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
但这似乎是一种垃圾方式。 我怎样才能纯粹在xaml中做到这一点,或者至少在C#中做到这一点?
通过查看源代码,我注意到TextBox
实际上不是文本框,而是Textbox的子类。 DelayTextBox
因此,您可以修改样式以定位该样式。
<Style TargetType="DelayTextBox">
<Setter Property="Foreground" Value="Blue" />
</Style>
我没有尝试过,但是应该可以。
更新资料
终于找到了问题。 样式应在其父样式中定义。
<Style TargetType="{x:Type filter:DataGridColumnFilter}">
<Style.Resources>
<Style TargetType="{x:Type support:DelayTextBox}">
<Setter Property="Foreground" Value="Blue" />
<Setter Property="FontWeight" Value="Bold"/>
</Style>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="Foreground" Value="Blue" />
<Setter Property="FontWeight" Value="Bold"/>
</Style>
</Style.Resources>
</Style>
我已经添加了comboxbox,因为我假设您也希望这样做。 您可以根据需要拿出二传手的粗体..正在使用它进行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.