开发者

Mixing OneTime and TwoWay binding

开发者 https://www.devze.com 2022-12-22 13:37 出处:网络
Suppose having this kind of CLR-objects: public class Foo { ... public Bar { get; private set; } } public class Bar: INotifyPropertyChanged

Suppose having this kind of CLR-objects:

public class Foo
{
    ...
    public Bar { get; private set; }
}

public class Bar: INotifyPropertyChanged
{
    public string Baz { get {...} set {...} }
}

Now I have a Window, with the DataContext bound to an instance of Foo. Within this Window I do:

<TextBox Text={Binding Bar.Baz} />

Because Foo doesn't implement INotifyPropertyChanged, I'll get a well known WPF memory leak here. There are two solutions:

  1. Implement INotifyPropertyChange on
  2. Foo Use a OneTime binding

I don't like 1), so let's say, we want to use a OneTime binding. But I only need the OneTime binding for accessing Bar while I need TwoWay binding for Baz:

<TextBox DataContext="{Binding Bar, Mode=OneTime}" Text={Binding Baz, Mode=TwoWay} />

So far so good, but if some other property from TextBox now needs to be bound to a property of Foo, things get complicated, because the DataCo开发者_StackOverflow中文版ntext isn't the Foo instance anymore.

So here's the question: Is there a way to specify a Bindig (in XAML or Code) that binds OneTime to a parent property and TwoWay to a child property?


Short answer- in XAML, probably not (without writing your own mark-up extension, at least), in code, sure, but it's not going to be of any use to you. Because your objects are not visually related (a Foo has a Bar but there is no way of knowing this in XAML), you would essentially just be hard-coding the binding, similar to how you are doing it now in the XAML.

Why are you opposed to implementing INotifyPropertyChanged on Foo?

0

精彩评论

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