我正在尝试做一些简单的事情——创建一个 DependencyProperty 然后绑定到它。但是,当我启动应用程序时,getter 似乎没有触发。(我猜这个解决方案会让我拍脑袋然后说“Doh!”,但仍然。:))
有任何想法吗?
代码隐藏代码:
public static readonly DependencyProperty PriorityProperty =
DependencyProperty.Register("Priority",
typeof (Priority), typeof (PriorityControl), null);
public Priority Priority
{
get { return (Priority)GetValue(PriorityProperty); }
set { SetValue(PriorityProperty, value); }
}
控制 XAML:
<ListBox Background="Transparent"
BorderThickness="0"
ItemsSource="{Binding Path=Priorities}"
Name="PriorityList"
SelectedItem="{Binding Path=Priority, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="16" Width="16">
<Border BorderBrush="Black"
BorderThickness="2"
CornerRadius="3"
Visibility="{Binding RelativeSource=
{RelativeSource Mode=FindAncestor, AncestorType=ListBoxItem}, Path=IsSelected, Converter={StaticResource boolToVisibilityConverter}}" />
<Border CornerRadius="3" Height="12" Width="12">
<Border.Background>
<SolidColorBrush Color="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBoxItem}, Path=Content, Converter={StaticResource priorityToColorConverter}}" />
</Border.Background>
</Border>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
绑定声明:
<UI:PriorityControl Grid.Column="8"
Priority="{Binding Path=Priority}"
VerticalAlignment="Center"/>
其他一些注意事项:
- 绑定在 UserControl 中
- UserControl 包含 PriorityControl
- PriorityControl 包含 DependencyProperty
- 我已经检查了 UserControl 的数据是否获得了适当的数据——所有其他绑定都有效。
- 如果我通过鼠标更改 PriorityControl 上的选择,一切都会适当触发。只是值的初始设置不起作用。
- 优先级是一个枚举。
编辑:我尝试了另外两件事。首先,我对值进行了双向绑定,但这不起作用。然后,我向依赖属性添加了一个属性更改回调,并使其调用 OnPropertyChanged,如下所示:
public static readonly DependencyProperty PriorityProperty =
DependencyProperty.Register("Priority", typeof (Priority), typeof (PriorityControl), new PropertyMetadata(HandleValueChanged));
private static void HandleValueChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var npc = dependencyObject as PriorityControl;
npc.OnPropertyChanged("Priority");
}
那也没有用。我什至尝试在控件上覆盖 ApplyTemplate 以强制属性更改通知,但该值永远不会在初始加载时设置。我可以改变价值观,看到一切都很好,但这是第一次什么都没有发生。