我希望能够在运行时向类添加属性,并稍后通过 BindingExtension 访问这些属性,例如:
class PropertiesHolder {
properties = [];
}
class PropertiesAdder {
propertiesHolder.properties.add(PropertyA);
propertiesHolder.properties.add(PropertyB);
}
Content="{Binding PropertyB}"
然后 XAML 将检索存储在对象“PropertyB”中的值
我面临的问题是没有办法区分这些不同的属性。我可以动态地将一堆数据放入 ObservableCollection 或其他东西中,但如果我创建两个或多个,我不知道如何通过数据绑定区分它们,因为 Binding 采用指向属性的路径。我不能说,在属性中存储 UID,因为显然,Binding 在第一次获取对象之前不会关心对象内部的信息。
看这个例子:
// This is the namespace for my implementation of the ViewModelBase class.
// Since you will have your own implementation or use some kind of package,
// you need to change this `using` to the one that is relevant for you.
using Simplified;
using System.Dynamic;
namespace Core2024.SO.ExpandoObjectTest
{
public class EOtestVM : ViewModelBase
{
public dynamic EO { get; }
private readonly IDictionary<string, object?> properties;
public EOtestVM()
{
properties = EO = new ExpandoObject();
}
public RelayCommand AddPropertyA => GetCommand(() => EO.PropertyA = 1, () => !properties.ContainsKey("PropertyA"));
public RelayCommand IncrementPropertyA => GetCommand(() => EO.PropertyA++, () => properties.ContainsKey("PropertyA"));
public RelayCommand AddPropertyB => GetCommand(() => properties.Add("PropertyB", 1), () => !properties.ContainsKey("PropertyB"));
public RelayCommand IncrementPropertyB => GetCommand(() => properties["PropertyB"] = ((int)properties["PropertyB"]) + 1, () => properties.ContainsKey("PropertyB"));
}
}
<Window x:Class="Core2024.SO.ExpandoObjectTest.EOtestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Core2024.SO.ExpandoObjectTest"
mc:Ignorable="d"
Title="EOtestWindow" Height="450" Width="800">
<Window.DataContext>
<local:EOtestVM/>
</Window.DataContext>
<UniformGrid Columns="2">
<Viewbox>
<TextBlock Text="{Binding EO.PropertyA}"/>
</Viewbox>
<Viewbox>
<TextBlock Text="{Binding EO.PropertyB}"/>
</Viewbox>
<Button Content="Add PropertyA" Command="{Binding AddPropertyA, Mode=OneWay}"/>
<Button Content="Add PropertyB" Command="{Binding AddPropertyB, Mode=OneWay}"/>
<Button Content="Increment PropertyA" Command="{Binding IncrementPropertyA, Mode=OneWay}"/>
<Button Content="Increment PropertyB" Command="{Binding IncrementPropertyB, Mode=OneWay}"/>
</UniformGrid>
</Window>