在 XAML 中,設置到靜態屬性的綁定很簡單......<TextBlock Text="{Binding Path=(foo:StaticClass.StaticProperty)}" />您如何在代碼中實現相同的目標?我嘗試了以下方法:var b = new Binding(){ Path = new PropertyPath(StaticClass.StaticProperty)};var b = new Binding(){ Path = new PropertyPath("StaticClass.StaticProperty")};var b = new Binding(){ Source = StaticClass, Path = new PropertyPath("StaticProperty")};...但以上都不起作用。這可以設置初始值,但不會更新......var binding = new Binding(){ Source = StaticClass.StaticProperty};到目前為止,我設法讓它工作的唯一方法就是這樣......public static Binding CreateStaticBinding(Type classType, string propertyName){ var xaml = $@" <Binding xmlns = ""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:is = ""clr-namespace:{$"{classType.Namespace};assembly={classType.Assembly.GetName().Name}"}"" Path=""(is:{classType.Name}.{propertyName})"" />"; return (Binding)System.Windows.Markup.XamlReader.Parse(xaml);}...但是 MAN 這讓我很惱火,我不得不求助于創建動態 XAML,然后解析它!?。。〉?,嘿......它的工作原理。我不得不認為有一個更簡單的方法!那是什么?
1 回答

心有法竹
TA貢獻1866條經驗 獲得超5個贊
PropertyPath通過 xaml paserer創建一個不同于Binding. 所以你應該使用下面的代碼來讓它工作。
var binding = new Binding() {
Path = new PropertyPath(typeof(StaticClass).GetProperty(nameof(StaticClass.StaticProperty))),
};
- 1 回答
- 0 關注
- 161 瀏覽
添加回答
舉報
0/150
提交
取消