开发者

Attributes from PropertyPath

If i have a PropertyPath, is it possible to get it's attributes? If not, what minimum of info do i need? From the example i need to get SomeAttribute. I need for it my custom binding class.

Eg.

Test.xaml

<TextBox Text={Binding SomeValue}/>

Test.xaml.cs

[SomeAttribute]
public string SomeValu开发者_如何学JAVAe { get; set; }


By PropertyPath you can take only property or subproperties. Read data binding overview for more information.


You can get an attribute of bound property with reflection technique.

The following is sample code.

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];
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜