ANewQuestionnaire ANewQuestionnaire - 1 month ago 15
C# Question

Data-Binding with Custom Dependency-Property of UserControl is not working

I have a

UserControl
with 2 custom
DependencyProperty
s (
ColumnsCount
,
RowsCount
):

public partial class CabinetGrid : UserControl
{

public static readonly DependencyProperty ColumnsCountProperty =
DependencyProperty.Register("ColumnsCount", typeof (int), typeof (CabinetGrid));

public static readonly DependencyProperty RowsCountProperty =
DependencyProperty.Register("RowsCount", typeof (int), typeof (CabinetGrid));

public int ColumnsCount
{
get { return (int) GetValue(ColumnsCountProperty); }
set { SetValue(ColumnsCountProperty, value); }
}
public int RowsCount
{
get { return (int) GetValue(RowsCountProperty); }
set { SetValue(RowsCountProperty, value); }
}
}


And here's the
DataBinding
:

<view:CabinetGrid Grid.Column="1" Grid.Row="2" x:Name="GridRack" ColumnsCount="{Binding SelectedRoom.ColumnCount}" />


whereas the window's
DataContext
has a property
SelectedRoom
which invokes
PropertyChanged-Event
.

Thru debugging, I got to know that the
DataContext
of the
UserControl
is set properly
.

However, when
SelectedRoom
has changed (=> I selected another item in a list), the
DependencyProperty
ColumnsCount
of my
UserControl
is not updated.
I am very frustrated, as I already spent an entire day debugging through this unexpected shit, using tools like
XAMLSpy
and
WpfSpoon
.

Please, help.




EDIT:

Clemens already pointed out, that a breakpoint in the
CLR-Property
wrapping the
DependencyProperty
(
ColumnsCount
) is not fired. This is a major issue, since I have to call some methods on the change. I'm trying to use the
PropertyChangedCallback
, but am currently experiencing some errors.

Answer

In order to get notified about value changes of a dependency property, you should specify a PropertyChangedCallback in the PropertyMetadata when you register the property.

public static readonly DependencyProperty ColumnsCountProperty =
    DependencyProperty.Register(
        "ColumnsCount", typeof(int), typeof(CabinetGrid),
         new PropertyMetadata(OnColumnsCountPropertyChanged));

private static void OnColumnsCountPropertyChanged(
    DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
     var cabinetGrid = (CabinetGrid)obj;

     // do something with the CabinetGrid instance
}
Comments