【发布时间】:2021-08-20 03:53:22
【问题描述】:
我有一个字符串source,我正试图将它从我的xaml 读入我的视图并分配给DependencyProperty。我收到一个错误Cannot access non-static property 'Source' in static context,我理解这个错误,但我不知道如何解决它。如果有人可以建议我如何将Source 更新为source 的值,请
public string Source
{
get { return (string)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
public static readonly DependencyProperty SourceProperty =
DependencyProperty.Register(
nameof(Source),
typeof(string),
typeof(TagsIndicator),
new PropertyMetadata(null, ReadInSource));
private static void ReadInSource(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
string source = e.NewValue.ToString();
Source = source; // Error here: Cannot access non-static property 'Source' in static context
}
【问题讨论】:
-
请注意,由于 NewValue 可以为空,
e.NewValue.ToString()应为e.NewValue as string或e.NewValue?.ToString()。
标签: c# wpf static dependency-properties non-static