在C#中使用XAML中的样式

时间:2019-05-03 12:10:49

标签: c# wpf listbox styles listboxitem

我在Window.Resources中有一种样式,希望在我的背后代码中使用:

XAML:

<Window.Resources>
    <Style x:Key="ListBoxItemStyle1" TargetType="ListBoxItem">
        <Setter Property="BorderBrush" Value="Red"/>
        <Setter Property="BorderThickness" Value="1"/>
    </Style>
</Window.Resources>

C#:

ListBoxItem lbi = new ListBoxItem();
lbi.Style = (Style)Application.Current.Resources["ListBoxItemStyle1"];
.
.
.
MyListBox.Items.Add(lbi);

但这不起作用,有什么解决方法吗?

1 个答案:

答案 0 :(得分:1)

如果您使用FindResourceTryFindResource方法,则无论您是在窗口中还是在全局中定义Style,都会找到lbi.Style = TryFindResource("ListBoxItemStyle1") as Style;

{
  "size": 0,
  "query": {
    ...
  },
  "aggs": {
    "UnitAggregationBucket": {
      "terms": {
        "field": "unitId",
        "size": 10,
        "order": {
          "score": "desc"
        }
      },
      "aggs": {
        "score": {
          "max": {
            "script": "_score"
          }
        }
      }
    }
  }
}