binding instanciated property to UI

时间:2015-09-14 15:37:29

标签: c# .net wpf

I have this class :

public class property : DependencyObject, INotifyPropertyChanged
{
    private string _myproperty;

    public string MyProperty
    {
        get
        {
            return this._myproperty;
        }
        set
        {
            this._myproperty = value;
            NotifyPropertyChanged("MyProperty");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string sproperty)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(sproperty));
        }
    }
}

In the main window I have created an instance of this class myclass xx = new myclass();, where I populate my property with string data and bind it to XAML like so:

<Window.Resources>
    <local:property x:Key="prop"></local:property>
</Window.Resources>

In my TextBox i have set the binding :

Text="{Binding Path=MyProperty, Source={StaticResource prop}}" BorderBrush="#FFC7CACC" />

This will not work unless if i use the existing resources:

var property = (local:property)Resources["prop"];

Is there another way to update the TextBox rather than using the resources? I want to use the normal class instantiation.

3 个答案:

答案 0 :(得分:0)

if you say Text="{Binding Path=MyProperty, Source={StaticResource prop}}" BorderBrush="#FFC7CACC" /> means that your VM is an instance of property class.

Try to surround your textbox with a Grid and set the grid dataContext with an instance of your poperty clas.

I mean

<Grid DataContext="from view or from behind assign your vm= new property()">
 <TextBox Text="{Binding Path=MyProperty" ....../>
</Grid>

答案 1 :(得分:0)

试试这个:

<Window.DataContext>
 <local:property/>
<Window.DataContext>

<TextBox Text="{Binding MyProperty}"/>

设置数据上下文后,只需尝试构建应用程序,如果可以在本地命名空间中找到属性类,则构建将成功。

构建应用程序后,如果成功,您可以尝试设置绑定,并且Intellisense将自动在“绑定选项”中显示MyProperty。

如果这不起作用,请尝试使用“属性”面板设置数据上下文和绑定。也许在视觉上你可以把事情搞定。

尝试一下,如果失败了,请告诉我哪里出错了

答案 2 :(得分:-1)

So this is what I have done, I have just bound to MyProperty, and applied the datacontext in the constructor using the instance of property class.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wpfApplication1="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
        <TextBox x:Name="MyTextBox" Text="{Binding Path=MyProperty}"  BorderBrush="#FFC7CACC" />

</Window>

Code Behind is as below :

 public property mydatacontext = null;
        public MainWindow()
        {
            InitializeComponent();

            mydatacontext = new property();
            this.DataContext = mydatacontext;

            mydatacontext.MyProperty = "Hello!!";

        }