在运行时更改背景后未加载wpf样式

时间:2012-09-27 11:08:30

标签: c# wpf xaml

我在网格中有两个网格。

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid x:Name="grid1" MouseLeftButtonDown="Grid_MouseLeftButtonDown" Grid.Column="0">
        <TextBlock  FontSize="50" Text="1" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    </Grid>
    <Grid x:Name="grid2"  MouseLeftButtonDown="Grid_MouseLeftButtonDown" Grid.Column="1">
        <TextBlock FontSize="50" Text="2" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    </Grid>
</Grid>

我正在使用此方法在运行时向网格添加样式。

private void StyleGrid()
{
    var converter = new System.Windows.Media.BrushConverter();

    Style myS = new System.Windows.Style();

    Setter setter1 = new Setter();
    setter1.Property = Grid.BackgroundProperty;
    setter1.Value = (Brush)converter.ConvertFromString("#3F3F46");
    myS.Setters.Add(setter1);


    Setter setter = new Setter();
    setter.Property = Grid.BackgroundProperty;
    setter.Value = (Brush)converter.ConvertFromString("#54545C");

    Trigger trigger = new Trigger();
    trigger.Property = Grid.IsMouseOverProperty;
    trigger.Value = true;
    trigger.Setters.Add(setter);
    myS.Triggers.Add(trigger);

    grid1.Style = myS;
    grid2.Style = myS;
}

我在InitializeComponent方法之后调用此方法。一切正常。

这是网格的MouseLeftButtonDown事件。

     private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    Grid senderGr = sender as Grid;

    StyleGrid();
    var converter = new System.Windows.Media.BrushConverter();

    var brush = (Brush)converter.ConvertFromString("#007ACC");


    senderGr.Background = brush;
}

此方法必须更改发件人网格的背景颜色,并且必须更改其他网格的样式。但它并没有改变风格。

如果您拥有Microsoft帐户,可以从SkyDrive下载和测试项目。谢谢。 https://skydrive.live.com/redir?resid=89FD450CC0CC74DA!168

1 个答案:

答案 0 :(得分:2)

直接设置背景将始终覆盖已定义的样式。 WPF使用一个set顺序来确定依赖属性的实际值(参见http://msdn.microsoft.com/en-us/library/ms743230.aspx

要获得结果,只需清除StyleGrid()方法中的设定值:

private void StyleGrid()
{
    grid1.ClearValue(Grid.BackgroundProperty);
    grid2.ClearValue(Grid.BackgroundProperty);
...