Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Run.Text bind two-way by default?

Tags:

c#

binding

wpf

In .NET 4.0, Run.Text is bindable. So I tried to bind it:

<Run Text="{Binding DisplayText}"/> 

But when I ran, I got an error: "A TwoWay or OneWayToSource binding cannot work on the read-only property 'DisplayText' of type 'SomeNamespace.SomeClass'."

My DisplayText property was indeed read-only, but so is a Run -- Runs go in in TextBlocks, which you can't edit. So why would I be getting this error? I dug into PresentationFramework with dotPeek and sure enough:

public static readonly DependencyProperty TextProperty =     DependencyProperty.Register("Text", typeof (string), typeof (Run),     (PropertyMetadata) new FrameworkPropertyMetadata((object) string.Empty,         FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,         new PropertyChangedCallback(Run.OnTextPropertyChanged),         new CoerceValueCallback(Run.CoerceText))); 

The fourth line, plain as day, specifies that Run.Text should bind two-way by default, which makes no sense and seems like a glaring design bug.

Of course, this is easy enough to work around:

<Run Text="{Binding DisplayText, Mode=OneWay}"/> 

But why should I have to work around it? Why does Run bind two-way by default?

like image 775
Joe White Avatar asked May 31 '11 15:05

Joe White


People also ask

What is the default binding mode in WPF?

Default Data-binding It just defines which is the default binding mode for the control's property. In WPF different controls has different default data-binding modes. For example, TextBlock's Text property has one-way as default binding mode but a TextBox's Text property has a two-way binding mode.

What are binding modes?

The binding mode defines how the data sources are bound. The different model implementations require specific binding modes. The resource model, for example, only supports one-time binding, that is, a binding from the model to the view.

What is mode TwoWay?

TwoWay: The target property will listen to the source property being changed and will update itself. AND The source property will listen to the target property being changed and will update itself.


1 Answers

Just a guess here:

It might be because Run objects are also used in the RichTextBox control, and I can imagine this control might want to Bind TwoWay by default!

like image 198
Arcturus Avatar answered Oct 02 '22 10:10

Arcturus