我正在使用TCP协议开发应用程序。 我想以不同的颜色显示通信的不同状态(connect = green,disconnect = red)
我定义了一个枚举:
public enum ComunicationStateTypeEnum
{
COMUNICATION_CONNECTED,
COMUNICATION_DISCONNECTED
};
我定义了一个转换类:
namespace Conversion
{
[ValueConversion(typeof(ComunicationStateTypeEnum), typeof(Brushes))]
public class ComStatusToColor : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
ComunicationStateTypeEnum state = (ComunicationStateTypeEnum)value;
if (state == ComunicationStateTypeEnum.COMUNICATION_CONNECTED)
return Brushes.Green;
return Brushes.Red;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
}
在Xaml中我定义了一个椭圆:
<Ellipse Name="ComEllipse" Height="25" Width="30" Fill ="{Binding Path=eCommStatus, Converter={StaticResource ComStatusToColor}}" Stroke="Black" DockPanel.Dock="Left"/>
也在我定义的Xaml中:
xmlns:ConversionNamespace="clr-namespace:Conversion"
<Window.Resources>
<ConversionNamespace:ComStatusToColor x:Key="ComStatusToColor"/>
</Window.Resources>
我想绑定到现有对象,因此我发起了:
ComEllipse.DataContext = SystemLogic.GetInstance();
(SystemLogic是单身人士)
并在SystemLogic中定义:
public class SystemLogic
{
public ComunicationStateTypeEnum eCommStatus { get; set; }
...
}
eCommStatus在构造函数中启动到COMUNICATION_DISCONNECTED,并且椭圆变为红色,并且当eCommStatus成员更改为COMUNICATION_CONNECTED时,椭圆不会更改其颜色
怎么了?
吉尔
答案 0 :(得分:2)
您需要在INotifyPropertyChanged
类中实现SystemLogic
接口,以让UI知道属性的值已更改。这样UI就可以自行更新。
public class SystemLogic : INotifyPropertyChanged
{
private ComunicationStateTypeEnum _eCommStatus;
public ComunicationStateTypeEnum eCommStatus
{
get
{
return _eCommStatus;
}
set
{
_eCommStatus = value;
RaisePropertyChanged("eCommStatus");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(String propertyName)
{
PropertyChangedEventHandler temp = PropertyChanged;
if (temp != null)
{
temp(this, new PropertyChangedEventArgs(propertyName));
}
}
}
答案 1 :(得分:0)
绑定没有错。但是SystemLogic必须实现INotifyPropertyChanged以便在更改时报告。
public class SystemLogic
{
private ComunicationStateTypeEnum _eCommStatus;
public ComunicationStateTypeEnum eCommStatus
{
get{return _eCommStatus;}
set
{
_eCommStatus = value;
OnPropertyChanged("ComunicationStateTypeEnum");
}
}
...
}