Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Binding Programmatically

I am attempting to convert this xaml binding to it's C# counterpart for various reasons:

<ListView x:Name="eventListView" Grid.Column="0" Grid.Row="1" Background="LightGray" BorderThickness="0">
    <local:EventCell x:Name="cell" Width="{Binding ActualWidth, Converter={StaticResource ListViewWidthConverter}, ElementName=eventListView, Mode=OneWay}"/>
</ListView>

I've read a lot of questions already that had similar problems and came up with this code:

Binding b = new Binding();
b.Source = eventListView;
b.Path = new PropertyPath(cell.Width);
b.Converter = new ListViewWidthConverter();
b.Mode = BindingMode.OneWay;
cell.SetBinding(ListView.ActualWidthProperty, b);

But the C# code won't compile, I am pretty lost as to why.

like image 466
xvpower Avatar asked Aug 08 '11 20:08

xvpower


People also ask

What is DataContext in WPF?

The DataContext property is the default source of your bindings, unless you specifically declare another source, like we did in the previous chapter with the ElementName property. It's defined on the FrameworkElement class, which most UI controls, including the WPF Window, inherits from.

How does binding work in WPF?

Data binding is a mechanism in WPF applications that provides a simple and easy way for Windows Runtime apps to display and interact with data. In this mechanism, the management of data is entirely separated from the way data. Data binding allows the flow of data between UI elements and data object on user interface.

What is binding path in WPF?

Binding path syntax. Use the Path property to specify the source value you want to bind to: In the simplest case, the Path property value is the name of the property of the source object to use for the binding, such as Path=PropertyName . Subproperties of a property can be specified by a similar syntax as in C#.

What is INotifyPropertyChanged in WPF?

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed. For example, consider a Person object with a property called FirstName .


1 Answers

In the constructor of the PropertyPath the cell.Width gets the value, you either want EventCell.ActualWidthProperty to get the DP-field if it is a DP, or use the string, "ActualWidth".

When translating XAML like this, just set the path in the Binding constructor which is the same constructor used in XAML (as the path is not qualified):

Binding b = new Binding("ActualWidth");

(If your binding were to be translated back to XAML it would be something like {Binding Path=123.4, ...}, note that the Path property is qualified as you did not use the constructor to set it)

Edit: Also the binding needs to be set on the EventCell.WidthProperty of course, you cannot set the ActualWidth, it seems your logic was inverted...

like image 58
H.B. Avatar answered Sep 21 '22 11:09

H.B.