21

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.

1
  • 1
    Why doesn't the code compile? What's the error? Commented Aug 8, 2011 at 20:56

2 Answers 2

23

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...

Sign up to request clarification or add additional context in comments.

2 Comments

Still gives me a XamlParseException was unhandled. with b.Path = new PropertyPath(EventCell.WidthProperty); or b.Path = new PropertyPath("ActualWidth");
@xvpower: See my edit (and PropertyPath(EventCell.WidthProperty) is wrong, that should be PropertyPath(EventCell.ActualWidthProperty))
0

I believe that you need to make the ActualWidthProperty throw a NotifyPropertyChanged event. Otherwise, the binding will not know to update when the property changes. Whenever I've done bindings, I've always had to implement INotifyPropertyChanged.

You might try extending the list view class and then implementing it on the width property. I gave a similar answer here: WPF Toolkit DataGrid column resize event

3 Comments

ActualWidth is probably already a DependencyProperty of the control.
Ah, it turns out that it is. In that case, you don't need to implement the property changed event
WPF bindings treat DependencyProperties differently (more efficiently) than INotifyPropertyChanged ones. So if DP there, use it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.