我正在尝试创建可应用于 Silverlight ComboBox 的附加行为。
我的行为是这样的:
using System.Windows.Controls;
using System.Windows;
using System.Windows.Controls.Primitives;
namespace AttachedBehaviours
{
public class ConfirmChangeBehaviour
{
public static bool GetConfirmChange(Selector cmb)
{
return (bool)cmb.GetValue(ConfirmChangeProperty);
}
public static void SetConfirmChange(Selector cmb, bool value)
{
cmb.SetValue(ConfirmChangeProperty, value);
}
public static readonly DependencyProperty ConfirmChangeProperty =
DependencyProperty.RegisterAttached("ConfirmChange", typeof(bool), typeof(Selector), new PropertyMetadata(true, ConfirmChangeChanged));
public static void ConfirmChangeChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
Selector instance = d as Selector;
if (args.NewValue is bool == false)
return;
if ((bool)args.NewValue)
instance.SelectionChanged += OnSelectorSelectionChanged;
else
instance.SelectionChanged -= OnSelectorSelectionChanged;
}
static void OnSelectorSelectionChanged(object sender, RoutedEventArgs e)
{
Selector item = e.OriginalSource as Selector;
MessageBox.Show("Unsaved changes. Are you sure you want to change teams?");
}
}
}
这在 XAML 中使用如下:
<UserControl x:Class="AttachedBehaviours.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:this="clr-namespace:AttachedBehaviours"
mc:Ignorable="d">
<Grid x:Name="LayoutRoot">
<StackPanel>
<ComboBox ItemsSource="{Binding Teams}"
this:ConfirmChangeBehaviour.ConfirmChange="true" >
</ComboBox>
</StackPanel>
</Grid>
</UserControl>
我收到一个错误:
元素 ComboBox 上的未知属性 ConfirmChangeBehaviour.ConfirmChange。[行:13 位置:65]
Intellisense 正在采取这种行为,为什么这在运行时会失败?
谢谢,马克
编辑: Register() 更改为 RegisterAttached()。出现同样的错误。