如果我有一个PropertyPath,可以获取它的属性吗?如果不是,我至少需要什么信息?从这个例子中,我需要获取SomeAttribute。我需要我的自定义绑定类。
例如:
Test.xaml
<TextBox Text={Binding SomeValue}/>Test.xaml.cs
[SomeAttribute]
public string SomeValue { get; set; }发布于 2011-02-17 18:34:50
通过PropertyPath,您只能获取属性或子属性。有关更多信息,请阅读data binding overview。
发布于 2011-02-18 20:52:40
你可以通过反射技术获得绑定属性的属性。
以下是示例代码。
SomeEntity.cs
public class SomeEntity
{
[SomeAttribute]
public string SomeValue { get; set; }
}MainWindow.xaml
<Window x:Class="WpfApplication4.MainWindow" ...>
<StackPanel>
<TextBox Name="textBox" Text="{Binding SomeValue}"/>
<Button Click="Button_Click">Button</Button>
</StackPanel>
</Window>MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new SomeEntity();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// Get bound object from TextBox.DataContext.
object obj = this.textBox.DataContext;
// Get property name from Binding.Path.Path.
Binding binding = BindingOperations.GetBinding(this.textBox, TextBox.TextProperty);
string propertyName = binding.Path.Path;
// Get an attribute of bound property.
PropertyInfo property = obj.GetType().GetProperty(propertyName);
object[] attributes = property.GetCustomAttributes(typeof(SomeAttribute), false);
SomeAttribute attr = (SomeAttribute)attributes[0];
}
}https://stackoverflow.com/questions/5027641
复制相似问题