WPF Related Question - Difference Between Properties and Fields

I have a question about how bindings work in WPF.

If I have a viewmodel with this property:

private string testString;
public string TestString
{
    get { return testString; }
    set { testString = value; }
}

Then if I bind it to xaml with something like this:

<TextBlock
    Text="{Binding Path=TestString, Mode=TwoWay}"
    Foreground="Red"
    HorizontalAlignment="Center"
    VerticalAlignment="Center"
    FontFamily="Calibri"
    FontSize="24"
    FontWeight="Bold">
</TextBlock>

It works ... Nothing new here.

However, if I remove the getters and setters from the test string and get something like this:

public string TestString;

The binding itself does not work. I do not know why this is happening, because for me it is equivalent to a public attribute of a public attribute with custom get and set.

Can someone shed light on this topic for me? :)

TYVM in advance!

PS: Sorry for my syntax. I just can't figure out how to work with a block of code.

+3
source share
3 answers

@, , - . , (Microsoft Developer Evangelist):

http://10rem.net/blog/2010/12/17/puff-the-magic-poco-binding-and-inotifypropertychanged-in-wpf

, PropertyDescriptor. , INotifyPropertyChanged viewmodel, :

private string testString;

public string TestString
{
    get { return testString; }
    set {
        if (testString != value) {
            testString = value;
            RaisePropertyChanged("TestString");
        }
    }
}

public event PropertyChangedEventHandler PropertyChanged;

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

, , 4 .

+2

TestString . , , , ( , , ).

, getter/setter, :

public string TestString { get; set; }
+3

I'm not sure if he should do something with INotifyPropertyChanged, maybe after uninstalling Get Set WPF will not be able to determine if the source has been changed or not. Or it was handled as a read-only property.

Please read this article.

http://msdn.microsoft.com/en-us/library/ms752347.aspx

http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

+2
source

All Articles