Reputation: 6544
I have a very basic question about binding between controls.
I have a class that has bunch of fields, lets call it "Style". One of the field is called "Images" with only getter and no setter. Then i have another class "StyleImages" that is called with constructor "new StyleImages (Style)" in getter on class "Style". Meaning that every time i call Images on Style i always get fresh Images created for current style.
In WPF i created a window. In XAML i have two controls. 1) Image control. 2) PropertyGrid control (from WF).
In code behind i create new instance of Style. In PropertyGrid i push entire "Style" while in Image control i push Style.Images.Image1
No what i want is when i change any attribute of "Style" in PropertyGrid i want that the Image control is refreshed.
What is the proper way to achieve this? If necessary i will paste some code also.
Upvotes: 0
Views: 173
Reputation: 6501
Whenever you need to notify the UI that data it is bound too has changed you need to do so through the INotifyPropertyChanged interface.
Typically I implement a base class called BindableObject that implements the interface for me. Then, anywhere I need to raise change notifications I inherit from BindableObject and call PropertyChange("Foo")
BindableObject looks like this:
public class BindableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void PropertyChange(String propertyName)
{
VerifyProperty(propertyName);
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
[Conditional("DEBUG")]
private void VerifyProperty(String propertyName)
{
Type type = GetType();
PropertyInfo info = type.GetProperty(propertyName);
if (info == null)
{
var message = String.Format(CultureInfo.CurrentCulture, "{0} is not a public property of {1}", propertyName, type.FullName);
//Modified this to throw an exception instead of a Debug.Fail to make it more unit test friendly
throw new ArgumentOutOfRangeException(propertyName, message);
}
}
}
Then When I need to call inside a property I have something like this (usually on the property setter)
private String foo;
public String Foo
{
get { return foo; }
set
{
foo = value;
PropertyChange("Foo");
}
Upvotes: 1
Reputation: 8708
You need to notify that the property has changed.
Consider implementing INotifyPropertyChanged and INotifyPropertyChanging.
Every time any other property changes, call OnPropertyChanged("ImageControl"). This way WFP framework will know the property changed and will act accordingly.
Also, make sure the Binding mode is correctly set, for debug purposes set it=TwoWay.
Upvotes: 1