【发布时间】:2020-05-21 10:03:34
【问题描述】:
我正在尝试将TextBlock 绑定到静态变量。我已经阅读了一些指南和主题,这就是我想出的,但到目前为止还没有结果。
XAML:
xmlns:SQLLog="clr-namespace:DBM.SQLServerLogHandler" //SQLServerLogHandler - folder with LogDisplay class
xmlns:Converters="clr-namespace:DBM.Converters"
...
<Window.Resources>
<Converters:StringListToStringConverter x:Key="ListToString"/>
</Window.Resources>
...
<TextBlock Grid.Row="1" Text="{Binding Source={x:Static SQLLog:LogDisplay.LogAdvanced}, Converter={StaticResource ListToString}}" FontSize="12"/>
静态类:
public static class LogDisplay
{
private static List<string> _logAdvanced;
public static List<string> LogAdvanced
{
get
{
return _logAdvanced;
}
set
{
if(value != _logAdvanced)
{
_logAdvanced = value;
if (StaticPropertyChanged != null)
StaticPropertyChanged(null, EventArgs.Empty);
}
}
}
public static event EventHandler StaticPropertyChanged;
}
和转换器
class StringListToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType != typeof(string))
throw new InvalidOperationException("The target must be a String");
return String.Join(", ", ((List<string>)value).ToArray());
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
我在TextBlock 也有错误Object reference not set to an instance of an object,但程序编译正确。
结果:
无论我在 _logAdvanced 变量中更改什么,TextBlock 都保持空白。
预期结果:
TextBlock 显示变量。
【问题讨论】:
-
更改属性也会更改字段。但是 TextBlock 仍然是空白的。