簡體   English   中英

根據具體對象的Color屬性設置WPF DataGridRow背景顏色

[英]Set WPF DataGridRow Background Color Based on a Color property of a concrete object

我已經多次問過這個問題,似乎在每種情況下都在xaml中設置顏色。 我已經在對象中以所需的方式映射了顏色。 請查看代碼:

public class Alert
{
     public Color BackgroundColor { get; set; }
     public DateTime Expires { get; set; }
     public string Event { get; set; }
     public string AreaDescription { get; set; }
}

然后,我有一個綁定到數據網格的警報列表。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();


        this.Alerts.Columns.Add(new DataGridTextColumn()
        {
            Header = "Expires",
            Binding = new Binding("Expires")
        });

        this.Alerts.Columns.Add(new DataGridTextColumn()
        {
            Header = "Event",
            Binding = new Binding("Event")
        });

        this.Alerts.Columns.Add(new DataGridTextColumn()
        {
            Header = "Area Description",
            Binding = new Binding("AreaDescription")
        });

        this.Alerts.ItemsSource = new FeatureCollection().GetFeatures().GetAlerts();
    }
}

我的xaml:

    <Grid>
    <DataGrid x:Name="Alerts" AutoGenerateColumns="False">
        <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
                <Setter Property="Background" Value="{Binding BackgroundColor}"/>
            </Style>
        </DataGrid.RowStyle>
    </DataGrid>
</Grid>

上面的行樣式設置器無效。 我也嘗試使用數據觸發器無濟於事。

應該發生的是,該行應從Alert類中的BackgroundColor屬性獲得其顏色。 在此行的那些鏈接方法內設置背景色“ new FeatureCollection()。GetFeatures()。GetAlerts();”。 該代碼未在此處列出,只是知道已經設置了顏色,例如BackgroundColor = Color.Yellow;。

任何幫助,將不勝感激。 我知道以前曾有人問過這個問題,但這些回答對我沒有用。 我肯定錯過了什么。

您的問題來自於BackGroundcolor不是Color而是畫筆的事實。 所以這可以工作:

public class Alert
{
    public SolidColorBrush BackgroundColor { get; set; }
    public DateTime Expires { get; set; }
    public string Event { get; set; }
    public string AreaDescription { get; set; }
}

也許是這樣的:

alerts.Add(new Alert() { BackgroundColor = new SolidColorBrush(Colors.Aqua)});
alerts.Add(new Alert() { BackgroundColor = new SolidColorBrush(Colors.Black) });
alerts.Add(new Alert() { BackgroundColor = new SolidColorBrush(Colors.Blue) });
alerts.Add(new Alert() { BackgroundColor = new SolidColorBrush(Colors.Yellow) });

如果您想要更精美的東西,可以使用“ Brush類型:

public Brush BackgroundColor { get; set; }

alerts.Add(new Alert() { BackgroundColor = new LinearGradientBrush(Colors.Black, Colors.Red, 30) });
alerts.Add(new Alert() { BackgroundColor = new SolidColorBrush(Colors.Black) });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM