c# - WPF - 在代码隐藏中更改样式

标签 c# wpf styles code-behind

我有一个显示 TFS 查询结果的列表框。我想在后面的代码中更改 ListBoxItem 的样式,以包含查询结果中的列。

ListBoxItem 的样式在我的 Windows.Resoruces 部分中定义。我试过这个:

public T GetQueryResultsElement<T>(string name) where T : DependencyObject
{
    ListBoxItem myListBoxItem =
        (ListBoxItem)(lstQueryResults.ItemContainerGenerator.ContainerFromIndex(0));

    // Getting the ContentPresenter of myListBoxItem
    ContentPresenter myContentPresenter =
        myListBoxItem.Template.LoadContent().FindVisualChild<ContentPresenter>();

    // Finding textBlock from the DataTemplate that is set on that ContentPresenter
    DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;  <------+
    T myControl = (T)myDataTemplate.FindName(name, myContentPresenter);       |
                                                                              |    
    return (T)myControl;                                                      |
}                                                                             |
                                                                              |
        ContentTemplate is null ----------------------------------------------+

但 ContentTemplate 为空。我从 here 得到了那个代码,然后使用 LoadContent 调用对其进行修改(原始代码为 ContentPresenter 指定了 null)。

无论如何。如果您知道在代码中更改现有样式的方法,我很乐意看到它。


如果你想要它们,请具体说明:
我打算在我的 ListBoxItem 样式中使用 WrapPanel。这就是我要添加额外的 TextBlock 项的内容。

这是我的风格的一部分:

<!--Checkbox ListBox-->
<Style x:Key="CheckBoxListStyle" TargetType="ListBox">
    <Style.Resources>
        <Style x:Key="ListBoxItemStyle" TargetType="ListBoxItem">
            <Setter Property="Tag" Value="{Binding Id}"/>
            <Setter Property="Background">
                <Setter.Value>
                    <Binding Path="Type" Converter="{StaticResource WorkItemTypeToColorConverter}" />
                </Setter.Value>
            </Setter>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Border BorderThickness="1" BorderBrush="#D4D4FF">
                            <Grid Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type WrapPanel}}, Path=ActualWidth}" ScrollViewer.CanContentScroll="True" Margin="2">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="20" />
                                    <ColumnDefinition Width="*" />
                                    <ColumnDefinition Width="30" />
                                </Grid.ColumnDefinitions>
                                <Grid.Background>
                                    <Binding Path="Type" Converter="{StaticResource WorkItemTypeToColorConverter}" />
                                </Grid.Background>

                                <CheckBox VerticalAlignment="Center" Grid.Column="0" IsChecked="{Binding IsSelected,
                                      RelativeSource={RelativeSource TemplatedParent},
                                      Mode=TwoWay}" Name="chkIsSelected" />
                                <WrapPanel Grid.Column="1" Margin="5,0,5,0" Name="QueryColumns">
                                    <TextBlock VerticalAlignment="Center"  Text="{Binding Id}" Name="txtID" />
                                    <TextBlock VerticalAlignment="Center" Margin="5,0,5,0" Text="{Binding Title}" Name="txtTitle" />
                                </WrapPanel>

最佳答案

您在这里违背了原则,试图在代码隐藏中直接操作视觉元素。有一个涉及数据绑定(bind)的非常简单的解决方案。

我会提供通用的解决方案,因为我不知道您的解决方案的细节。

获得查询结果后,创建一个枚举,返回一个列名,并为每次迭代返回一个字段值。

示例:

class NameValuePair 
{
    public string Name { get; set; }
    public object Value { get; set; }
}

public IEnumerable<IEnumerable<NameValuePair>> EnumerateResultSet(DataTable resultSet)
{
    foreach (DataRow row in resultSet.Rows)
        yield return EnumerateColumns(resultSet, row);
}

public IEnumerable<NameValuePair> EnumerateColumns(DataTable resultSet, DataRow row)
{
    foreach (DataColumn column in resultSet.Columns)
        yield return new NameValuePair
            { Name = column.ColumnName, Value = row[column] };
}

在您的代码隐藏中,一旦您获得 DataTable 结果集,请执行以下操作:

myResultsList.ItemsSource = EnumerateResultSet(myDataTable);

XAML 可能如下所示:

<Window.Resources>
    <DataTemplate x:Key="ColumnTemplate">
        <Border BorderBrush="Black" BorderThickness="1" CornerRadius="2" Padding="2">
            <WrapPanel>
                <TextBlock Text="{Binding Name}" Margin="0,0,5,0"/>
                <TextBlock Text="{Binding Value}" Margin="0,0,10,0"/>
            </WrapPanel>
        </Border>
    </DataTemplate>
    <DataTemplate x:Key="RowTemplate">
        <Grid>
            <ItemsControl 
                ItemsSource="{Binding}" 
                ItemTemplate="{StaticResource ColumnTemplate}"
                Margin="0,5,0,5"/>
        </Grid>
    </DataTemplate>
</Window.Resources>
<Grid>
    <ListBox Name="myResultsList" ItemTemplate="{StaticResource RowTemplate}"/>
</Grid>

示例输出:

Sample Output Image

关于c# - WPF - 在代码隐藏中更改样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1971149/

相关文章:

c# - ASP.NET MVC3 - 存储 IsAdmin 信息的最合适方法

WPF 选项卡控件 : Sliding effect on tab item selection

wpf - VS 2010 : Exceptions when XAML file of project that includes System. Windows.Interactivity 已打开

delphi - 修复 Delphi XE3 中的 VCL 样式目录

c# - 来自代码的带有样式和 DateTriggers 的 DataTemplate

具有生成器模式的 C# 代码契约(Contract) - "Possibly calling a method on a null reference"

c# - 使用负等式表达式的 resharper 自定义模式替换

c# - 如何调试我的 TFS 事件?

c# - WPF MVVM 命令可以执行启用/禁用按钮

javascript - 将 iframe 定位在页 footer 分上方。简单的