如何在WPF中设计子类组件的样式



我在WPF/XAML中有一个TextBox的子类,我希望对它应用与我对所有其他TextBox实例相同的样式。我定义了以下样式的

<Style TargetType="TextBox" x:Key="basicTextBox" >
    <Setter Property="Controls:TextBoxBehaviours.UpdateWhenEnterPressed" Value="True"/>
    <Setter Property="Controls:TextBoxBehaviours.SelectAllWhenEnterPressed" Value="True"/>
    <Setter Property="Controls:TextBoxBehaviours.SelectAllOnFocus" Value="True"/>
</Style>

和一个类TextBoxBehaviours来实现这些

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Reactive.Linq;
namespace Weingartner.Controls
{
    public static class TextBoxBehaviours
    {
        static TextBoxBehaviours()
        {}
        #region Binding Support
        private static Dictionary<Tuple<TextBox,string>, IDisposable> Bindings 
            = new Dictionary<Tuple<TextBox,string>, IDisposable>();
        private static void Bind(TextBox tb, string key, IDisposable d)
        {
            Bindings[Tuple.Create(tb, key)] = d;
        }
        private static void UnBind(TextBox tb, string key)
        {
            var t = Tuple.Create(tb, key);
            if (Bindings.ContainsKey(t))
            {
                var d = Bindings[t];
                Bindings.Remove(t);
                d.Dispose();
            }
        }
        #endregion
        static UIPropertyMetadata CreateMeta<T>(bool defaultValue, Action<T,DependencyPropertyChangedEventArgs> fn)
        where T : DependencyObject
        {
            return new UIPropertyMetadata(defaultValue, (o, e) =>{
                var t = o as T;
                if (t == null)
                {
                    return;
                }
                fn(t, e);
            });
        }
        #region Update When Enter Pressed
        public static readonly DependencyProperty 
            UpdateWhenEnterPressedProperty = 
            DependencyProperty.RegisterAttached
            ( "UpdateWhenEnterPressed"
            , typeof(bool)
            , typeof(TextBoxBehaviours)
            , CreateMeta<TextBox>(false, SetupUpdateOnEnterPressed));
        public static void 
            SetUpdateWhenEnterPressed
            ( TextBox dp
            , bool value)
        {
            dp.SetValue(UpdateWhenEnterPressedProperty, value);
        }
        public static bool 
            GetUpdateWhenEnterPressed
            ( TextBox dp)
        {
            return (bool)dp.GetValue(UpdateWhenEnterPressedProperty);
        }
        private static void 
            SetupUpdateOnEnterPressed
            ( TextBox element
            , DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
            {
                var sub = element
                    .PreviewKeyDownObserver()
                    .Where(x=>x.EventArgs.Key==Key.Enter)
                    .Subscribe(x=>DoUpdateSource(element));
                Bind(element, "KeyEnter", sub);
            }else{
                UnBind(element, "KeyEnter");
            }
        }
        static void DoUpdateSource(TextBox source)
        {
            BindingExpression binding = BindingOperations.GetBindingExpression(source, TextBox.TextProperty);
            if (binding != null)
            {
                binding.UpdateSource();
            }
        }
        #endregion
        #region SelectAll When Enter Pressed
        public static readonly DependencyProperty 
            SelectAllWhenEnterPressedProperty = 
            DependencyProperty.RegisterAttached
            ( "SelectAllWhenEnterPressed"
            , typeof(bool)
            , typeof(TextBoxBehaviours)
            , CreateMeta<TextBox>(false, SetupSelectAllOnEnterPressed));
        public static void 
            SetSelectAllWhenEnterPressed
            ( TextBox dp
            , bool value)
        {
            dp.SetValue(SelectAllWhenEnterPressedProperty, value);
        }
        public static bool 
            GetSelectAllWhenEnterPressed
            ( TextBox dp)
        {
            return (bool)dp.GetValue(SelectAllWhenEnterPressedProperty);
        }
        private static void 
            SetupSelectAllOnEnterPressed
            ( TextBox element
            , DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
            {
                var sub = element
                    .PreviewKeyDownObserver()
                    .Where(x=>x.EventArgs.Key==Key.Enter)
                    .Subscribe(x=>element.SelectAll());
                Bind(element, "KeyEnterSelectAll", sub);
            }else{
                UnBind(element, "KeyEnterSelectAll");
            }
        }
        #endregion
        #region Select All On Focus
        public static readonly DependencyProperty 
            SelectAllOnFocusProperty = 
            DependencyProperty.RegisterAttached
            ( "SelectAllOnFocus"
            , typeof(bool)
            , typeof(TextBoxBehaviours)
            , CreateMeta<TextBox>(false, SetupSelectAllOnFocus));

        public static void 
            SetSelectAllOnFocus
            ( TextBox dp
            , bool value)
        {
            dp.SetValue(SelectAllOnFocusProperty, value);
        }
        public static bool 
            GetSelectAllOnFocus
            ( TextBox dp)
        {
            return (bool)dp.GetValue(SelectAllOnFocusProperty);
        }
        private static void 
            SetupSelectAllOnFocus
            ( TextBox element
            , DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
            {
                Bind(element, "Focus", element.GotFocusObserver().Subscribe(x => element.SelectAll()));
            }else{
                UnBind(element, "Focus");
            }
        }
        #endregion
    }
}

在我的XAML文件中,我一直在做

<Style TargetType="TextBox" BasedOn="{StaticResource basicTextBox}"/>

下面的所有文本框都得到了我想要的行为。考虑到我的子类也是一个TextBox类,我认为它们也会得到行为,但它们没有。我试着通过扩展样式来显式

<Style TargetType="TextBox" BasedOn="{StaticResource basicTextBox}"/>
<Style TargetType="Controls:EditForLength">
    <Setter Property="Controls:TextBoxBehaviours.UpdateWhenEnterPressed" Value="True"/>
    <Setter Property="Controls:TextBoxBehaviours.SelectAllWhenEnterPressed" Value="True"/>
    <Setter Property="Controls:TextBoxBehaviours.SelectAllOnFocus" Value="True"/>
</Style>

但我得到一个错误,告诉我EditForLength 的密钥

System.ArgumentException occurred
  HResult=-2147024809
  Message=Item has already been added. Key in dictionary: 'Weingartner.Controls.EditForLength'  Key being added: 'Weingartner.Controls.EditForLength'
  Source=mscorlib
  StackTrace:
       at System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add)
  InnerException: 

因此,总的来说,通过父类上的样式安装的行为并不适合子类实例,但当试图添加另一个针对子类的样式时,会出现一些字典错误。

注意,我已经在EditForLength控件的实例上尝试了行为显式,它们工作得很好。我只是无法通过造型来安装行为。

更新

我发现即使在所有重要的地方我也会出错除了样式声明被注释掉

        <!--<Style TargetType="TextBox" BasedOn="{StaticResource basicTextBox}"/>-->
        <Style TargetType="Controls:EditForLength">
            <!--
            <Setter Property="Controls:TextBoxBehaviours.UpdateWhenEnterPressed" Value="True"/>
            <Setter Property="Controls:TextBoxBehaviours.SelectAllWhenEnterPressed" Value="True"/>
            <Setter Property="Controls:TextBoxBehaviours.SelectAllOnFocus" Value="True"/>
             -->
        </Style>

关于异常:您似乎已经在dictionary(或其合并的dictionary)中添加了此样式-尝试搜索它,我相信您会找到具有相同关键字的样式。

关于隐式样式:它们不应用于目标类型的子类(试着想象一下,如果它们被应用了——如果你已经为FrameworkElement创建了隐式样式——你的控件的大部分布局将被破坏)

相关内容

  • 没有找到相关文章

最新更新