问题
我在MainWindow
上有一个ComboBox
和ToggleButton
,它们的SelectedIndex
和IsChecked
属性分别具有双向绑定。它们绑定的属性是DependencyProperties(DP),我在setter上有一个断点,但调试器从未停止过。我应该注意,绑定应该在DP上的Initializer工作时工作,转换器也工作。另外,VS的输出窗口也没有什么问题。
XAML
<ToggleButton x:Name="tbSortDirection" Width="25" IsChecked="{Binding Path=SortDirection,Converter={StaticResource LDB},Mode=TwoWay,ElementName=mwa,UpdateSourceTrigger=PropertyChanged}">
<ed:RegularPolygon Fill="#FF080808" Height="5" UseLayoutRounding="True" Margin="-2,0,0,0" PointCount="3" Width="6"/>
</ToggleButton>
<ComboBox x:Name="cbSort" Width="100" VerticalAlignment="Stretch" Margin="-5,0,0,0" SelectedIndex="{Binding SelSortIndex,Mode=TwoWay,ElementName=mwa,UpdateSourceTrigger=PropertyChanged}" IsSynchronizedWithCurrentItem="True" >
<ComboBoxItem Content="a"/>
<ComboBoxItem Content="b"/>
<ComboBoxItem Content="v"/>
<ComboBoxItem Content="f"/>
</ComboBox>
代码隐藏(DP)
public ListSortDirection SortDirection
{
get { return (ListSortDirection)GetValue(SortDirectionProperty); }
set // BreakPoint here
{
MessageBox.Show("");
SetValue(SortDirectionProperty, value);
UpdateSort();
}
}
public static readonly DependencyProperty SortDirectionProperty =
DependencyProperty.Register("SortDirection", typeof(ListSortDirection), typeof(MainWindow), new PropertyMetadata(ListSortDirection.Ascending));
public int SelSortIndex
{
get { return (int)GetValue(SelSortIndexProperty); }
set // BreakPoint here
{
MessageBox.Show("");
SetValue(SelSortIndexProperty, value);
UpdateSort();
}
}
public static readonly DependencyProperty SelSortIndexProperty =
DependencyProperty.Register("SelSortIndex", typeof(int), typeof(MainWindow), new PropertyMetadata(1));
它不会中断,因为WPF将在DependencyProperty
上直接调用GetValue
和SetValue
。如果您想在属性更改时执行某些操作,则需要定义属性更改时的回调:
public static readonly DependencyProperty SortDirectionProperty =
DependencyProperty.Register("SortDirection",
typeof(ListSortDirection),
typeof(MainWindow),
new PropertyMetadata(ListSortDirection.Ascending, SortDirectionPropertyChangedCallback));
private static void SortDirectionPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
(d as MainWindow).SortDirectionPropertyChangedCallback(e);
}
private void SortDirectionPropertyChangedCallback(DependencyPropertyChangedEventArgs e)
{
UpdateSort();
}
public ListSortDirection SortDirection
{
get { return (ListSortDirection)GetValue(SortDirectionProperty); }
set { SetValue(SortDirectionProperty, value); }
}
你真的在调用setters吗?
例如,说
SortDirection = someOtherSortDirection;
会进入你的二传手,但
SortDirection.SomeProperty = something;
实际上是通过你的吸气剂。
在getter中设置一个断点,如果在您认为setter应该是的时候调用它,我不会感到惊讶。