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.
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.
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.
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#.
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 .
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With