0

我在一个网格中有两个网格。

<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

4

1 回答 1

2

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

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

private void StyleGrid()
{
    grid1.ClearValue(Grid.BackgroundProperty);
    grid2.ClearValue(Grid.BackgroundProperty);
...
于 2012-09-27T12:33:38.447 回答