【问题标题】:How to set the style programmatically如何以编程方式设置样式
【发布时间】:2010-07-07 22:33:36
【问题描述】:

我有以下风格,但我需要以编程方式制作:

<xcdg:DataGridControl MinHeight="300" 
                      Name="listViewUnallocated" 
                      ItemsSource="{Binding Source={StaticResource
                                         cvs_unallocatedTerminals}}"
                      AllowDrop="True" 
                      Drop="Grid_Drop" 
                      MouseMove="Grid_MouseMove" 
                      KeyUp="listViewUnallocated_KeyUp"
                      MouseDoubleClick="gridUnallocated_MouseDoubleClick"
                      ReadOnly="True"
                      DockPanel.Dock="Top">
    <xcdg:DataGridControl.Resources>
        <Style TargetType="{x:Type xcdg:DataRow}" x:Name="selectedStyleTrigger">
            <Style.Triggers>
                <DataTrigger Binding="{Binding TerminalId}" Value="72948028">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </xcdg:DataGridControl.Resources>

【问题讨论】:

    标签: wpf


    【解决方案1】:

    在控件的代码隐藏文件中,尝试:

    this.Style = Resources["ResourceName"] as Style;
    

    【讨论】:

    • FindResource("ResourceName") 和 Resources["ResourceName"] 有什么区别?
    • 有了这个我无法在 Window 的构造函数中找到样式,但我可以使用FindResourcemethod。 (它是一个抽象类,在多个地方继承,没有定义 XAML。)
    • 我认为这样做不是个好主意。如果真的要这样做,那么我至少会在 XAML 文件中添加如下评论:&lt;!-- this ressource is used in code behind, don't change the name --&gt;。否则我会在后面的代码中完全实现它。
    【解决方案2】:

    在 XAML 和代码隐藏使用中设置 x:Key

    something.Style = (Style) FindResource("YourResourceKey");
    

    【讨论】:

      【解决方案3】:

      您好,我们可以像这样以编程方式设置样式。

      Style rowStyle = new Style(typeof(DataGridRow));
      
      DataTrigger dataTrigger = new DataTrigger("TerminalId");
      Binding binding = new Binding();
      dataTrigger.Binding = binding;
      dataTrigger.Value = 72948028;
      
      Setter setter = new Setter(DataGridRow.BackgroundProperty, Brushes.Red);
      
      dataTrigger.Setters.Add(setter);
      
      rowStyle.Triggers.Add(dataTrigger);
      listViewUnallocated.RowStyle = rowStyle;
      

      【讨论】:

        猜你喜欢
        • 2013-02-07
        • 1970-01-01
        • 2017-03-11
        • 2012-04-12
        • 2020-10-06
        • 2011-03-09
        • 2014-09-20
        • 2015-07-04
        相关资源
        最近更新 更多