我是WPF的新手并且有点迷失。
我想在标签中显示Text,将其绑定到以下类:
class Status
{
public string Message;
public bool Success;
}
我希望标签在成功时以绿色显示“消息”,如果不成功则以红色显示。我不知道如何开始。
答案 0 :(得分:1)
首先,您需要绑定到属性,而不是成员。您还应养成在您的课程中实施INotifyPropertyChanged
的习惯。
public class Status : INotifyPropertyChanged
{
private string message;
public string Message
{
get { return this.message; }
set
{
if (this.message == value)
return;
this.message = value;
this.OnPropertyChanged("Message");
}
}
private bool success;
public bool Success
{
get { return this.success; }
set
{
if (this.success == value)
return;
this.success = value;
this.OnPropertyChanged("Success");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
在绑定方面,您必须使用自定义IValueConverter
public class RGColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return null;
bool success = (bool) value;
return success ? Brushes.Green : Brushes.Red;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
相关的绑定/设置
<Window.Resources>
<wpfApplication2:RGColorConverter x:Key="colorConverter" />
</Window.Resources>
<Label Content="{Binding Message}" Foreground="{Binding Success, Converter={StaticResource colorConverter}}" />