C# 订阅属性更改事件以更新TextBlock的样式
我有一个映射到视图的C# 订阅属性更改事件以更新TextBlock的样式,c#,wpf,events,C#,Wpf,Events,我有一个映射到视图的LoggingService。一旦修改,它将显示一些文本 到目前为止,它工作正常,但是我想根据LoggingType修改我文本的颜色 我的问题是,我找不到应该订阅LoggingService属性更改事件以调用以下UpdateTextStyle方法的位置: private void UpdateTextStyle(ILoggingService logging, string propertyName) { var loggingType = l
LoggingService
。一旦修改,它将显示一些文本
到目前为止,它工作正常,但是我想根据LoggingType
修改我文本的颜色
我的问题是,我找不到应该订阅LoggingService属性更改事件以调用以下UpdateTextStyle
方法的位置:
private void UpdateTextStyle(ILoggingService logging, string propertyName)
{
var loggingType = logging.GetUserLevelLatestLog().Key;
switch (loggingType)
{
case LoggingTypes.Error:
View.UserInfoLogsTextBlock.Foreground = new SolidColorBrush(Colors.Red);
View.UserInfoLogsTextBlock.FontWeight = FontWeights.Bold;
break;
...
}
}
以下是映射到我的虚拟机中我的视图的属性:
public ILoggingService LoggingService
{
get
{
if (_loggingService == null)
{
_loggingService = Model.LoggingService;
}
return _loggingService;
}
}
提前谢谢 除非您知道自己在WPF中做什么,否则不要在属性更改事件上使用。您将导致内存泄漏 我假设您已将
日志服务
绑定到(我假设)XAML中的文本框
因此,我建议您为LoggingTypes
创建一个IValueConverter
,然后通过转换器将TextBox.Style
绑定到LoggingService.LoggingType
<UserControl>
<UserControl.Resources>
<LoggingStyleConverter x:Key="LoggingStyleConverter" />
</UserControl.Resources>
<TextBox
Text="{Binding Path=Foo.Bar.LoggingService.Text}"
Style="{Binding Path=Foo.Bar.LoggingService.Type
Converter={StaticResource LoggingStyleConverter}}"
/>
</UserControl>
public class LoggingStyleConverter : IValueConverter
{
public object Convert(object value, blah blah blah)
{
var type = (LoggingTypes)value;
switch (type)
{
case blah:
return SomeStyle;
default:
return SomeOtherStyle;
}
}
}
公共类LoggingStyleConverter:IValueConverter
{
公共对象转换(对象值,等等)
{
变量类型=(LoggingTypes)值;
开关(类型)
{
案例无稽之谈:
回归风格;
违约:
返回其他样式;
}
}
}
除非您知道自己在WPF中做什么,否则不要在属性更改事件上使用。您将导致内存泄漏
我假设您已将日志服务
绑定到(我假设)XAML中的文本框
因此,我建议您为LoggingTypes
创建一个IValueConverter
,然后通过转换器将TextBox.Style
绑定到LoggingService.LoggingType
<UserControl>
<UserControl.Resources>
<LoggingStyleConverter x:Key="LoggingStyleConverter" />
</UserControl.Resources>
<TextBox
Text="{Binding Path=Foo.Bar.LoggingService.Text}"
Style="{Binding Path=Foo.Bar.LoggingService.Type
Converter={StaticResource LoggingStyleConverter}}"
/>
</UserControl>
public class LoggingStyleConverter : IValueConverter
{
public object Convert(object value, blah blah blah)
{
var type = (LoggingTypes)value;
switch (type)
{
case blah:
return SomeStyle;
default:
return SomeOtherStyle;
}
}
}
公共类LoggingStyleConverter:IValueConverter
{
公共对象转换(对象值,等等)
{
变量类型=(LoggingTypes)值;
开关(类型)
{
案例无稽之谈:
回归风格;
违约:
返回其他样式;
}
}
}
非常感谢,它工作得非常好!(已经在VM构造函数中注册了我的事件并正常工作,但肯定是内存泄漏,而且编码也不好)非常感谢,它工作得非常好!(已在VM构造函数中注册到我的事件并正在工作,但肯定是内存泄漏,而且编码也不好)