Tôi đang cố sử dụng thuộc tính đính kèm để kích hoạt thay đổi kiểu trên số UIElement
khi sự kiện đã kích hoạt.Thuộc tính đính kèm để cập nhật trình kích hoạt kiểu trên sự kiện
Đây là trường hợp kịch bản:
Một người dùng thấy một TextBox
, và tập trung sau đó unfocuses nó. Một nơi nào đó trong một tài sản đính kèm nó thông báo sự kiện này LostFocus
và đặt một tài sản (một nơi nào đó?) Để nói rằng nó HadFocus
.
Kiểu trên Hộp văn bản sau đó biết rằng nó nên tự tạo kiểu khác nhau dựa trên thuộc tính HadFocus này.
Đây là cách tôi tưởng tượng đánh dấu để tìm ...
<TextBox Behaviors:UIElementBehaviors.ObserveFocus="True">
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Behaviors:UIElementBehaviors.HadFocus" Value="True">
<Setter Property="Background" Value="Pink"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
Tôi đã thử một vài sự kết hợp của các tài sản gắn liền để làm việc này, nỗ lực mới nhất của tôi ném một XamlParseException
nêu "Thuộc tính không thể rỗng trên Trình kích hoạt".
public class UIElementBehaviors
{
public static readonly DependencyProperty ObserveFocusProperty =
DependencyProperty.RegisterAttached("ObserveFocus",
typeof (bool),
typeof (UIElementBehaviors),
new UIPropertyMetadata(false, OnObserveFocusChanged));
public static bool GetObserveFocus(DependencyObject obj)
{
return (bool) obj.GetValue(ObserveFocusProperty);
}
public static void SetObserveFocus(DependencyObject obj, bool value)
{
obj.SetValue(ObserveFocusProperty, value);
}
private static void OnObserveFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var element = d as UIElement;
if (element == null) return;
element.LostFocus += OnElementLostFocus;
}
static void OnElementLostFocus(object sender, RoutedEventArgs e)
{
var element = sender as UIElement;
if (element == null) return;
SetHadFocus(sender as DependencyObject, true);
element.LostFocus -= OnElementLostFocus;
}
private static readonly DependencyPropertyKey HadFocusPropertyKey =
DependencyProperty.RegisterAttachedReadOnly("HadFocusKey",
typeof(bool),
typeof(UIElementBehaviors),
new FrameworkPropertyMetadata(false));
public static readonly DependencyProperty HadFocusProperty = HadFocusPropertyKey.DependencyProperty;
public static bool GetHadFocus(DependencyObject obj)
{
return (bool)obj.GetValue(HadFocusProperty);
}
private static void SetHadFocus(DependencyObject obj, bool value)
{
obj.SetValue(HadFocusPropertyKey, value);
}
}
Bất kỳ ai cũng có thể hướng dẫn tôi?
Đó là bản sửa lỗi, cảm ơn sự giúp đỡ của bạn: o) – mortware