我從代碼隱藏中的變量中獲取多個項目的狀態,並且想要在我的GUI中的每個選項卡上以圖形方式顯示這些項目的狀態。我將狀態顯示爲彩色標籤(3種不同的顏色代表3種不同的狀態)。我已經想出瞭如何強制背景用一堆代碼改變顏色,但我認爲使用數據觸發器會更好,但是我一直無法讓它工作。使用調試器,它逐步完成例程並正確更改值,但屏幕上的顏色不會改變。順便說一下,我一直在使用wpf和C#大約6周。預先感謝您指出我的錯誤。如何將Label.Background綁定到變量
這裏是我的類:
class componentStatus : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private int _icc1status;
public int Icc1status
{
get
{
return this._icc1status;
}
set
{
if (value != this._icc1status)
{
this._icc1status = value;
NotifyPropertyChanged("Icc1status");
}
}
}
private int _icc2status;
public int Icc2status
{
get
{
return this._icc2status;
}
set
{
if (value != this._icc2status)
{
this._icc2status = value;
NotifyPropertyChanged("Icc2status");
}
}
}
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
這裏的XAML:
<Style x:Key="Icc2Status" TargetType="{x:Type Label}">
<Style.Triggers>
<DataTrigger Binding="{Binding Icc2status, UpdateSourceTrigger=PropertyChanged}" Value="2">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
<DataTrigger Binding="{Binding Icc2status, UpdateSourceTrigger=PropertyChanged}" Value="1">
<Setter Property="Background" Value="Yellow"/>
</DataTrigger>
<DataTrigger Binding="{Binding Icc2status, UpdateSourceTrigger=PropertyChanged}" Value="0">
<Setter Property="Background" Value="Green"/>
</DataTrigger>
</Style.Triggers>
</Style>
<Label x:Name="icc2statusLabel" Style="{DynamicResource Icc2Status}" Content="ICC 2" HorizontalContentAlignment="Center" HorizontalAlignment="Right" Margin="0,0,260,0" VerticalAlignment="Top" Width="45" Foreground="Black" BorderThickness="1" BorderBrush="Black"/>
而且我後面的代碼:
public partial class MainWindow : Window
{
componentStatus compStatus = new componentStatus();
public static readonly DependencyProperty myComponentProperty =
DependencyProperty.Register("Icc2status", typeof(int), typeof(Label), new PropertyMetadata(null));
//GUI for Invent Program
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
//This button is for test purposes only
private void test_Click(object sender, RoutedEventArgs e)
{
compStatus.Icc1status = 2;
compStatus.Icc2status = 1;
}
//Routine to force color change of the system state when it changes
//I think data triggers are probably a better option
private void component_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
//Get the new component status
//if (compStatus.Icc1status == 0) icc1statusLabel.Background = new SolidColorBrush(Colors.Green);
//if (compStatus.Icc1status == 1) icc1statusLabel.Background = new SolidColorBrush(Colors.Yellow);
//if (compStatus.Icc1status == 2) icc1statusLabel.Background = new SolidColorBrush(Colors.Red);
}
}
完美地工作。感謝您及時的回覆。我被困在這個3天。 – mkk 2014-11-03 17:58:24