精华内容
下载资源
问答
  • WPF自定义控件依赖属性怎么实时变化。

    WPF 自定义的依赖属性要想在界面上能立即看到属性变化的值。必须实现回调通知


    下面以最近刚自定义的RadioButton为例


    public class RadioButton360 : RadioButton
        {
            public static readonly DependencyProperty CheckedColorProperty = DependencyProperty.Register("CheckedColor", typeof(Brush), typeof(RadioButton360), new PropertyMetadata(Brushes.White, PropertyChanged));
            public static readonly DependencyProperty UnCheckedColorProperty = DependencyProperty.Register("UnCheckedColor", typeof(Brush), typeof(RadioButton360), new PropertyMetadata(Brushes.Transparent, PropertyChanged));
            public static readonly DependencyProperty MouseOverColorProperty = DependencyProperty.Register("MouseOverColor", typeof(Brush), typeof(RadioButton360), new PropertyMetadata(Brushes.LightGray, PropertyChanged));
    
            /// <summary>
            /// 选中颜色
            /// </summary>
            public Brush CheckedColor
            {
                get { return (Brush)GetValue(CheckedColorProperty); }
                set { SetValue(CheckedColorProperty, value); }
            }
    
            /// <summary>
            /// 未选中颜色
            /// </summary>
            public Brush UnCheckedColor
            {
                get { return (Brush)GetValue(UnCheckedColorProperty); }
                set { SetValue(UnCheckedColorProperty, value); }
            }
    
            /// <summary>
            /// 鼠标移动颜色
            /// </summary>
            public Brush MouseOverColor
            {
                get { return (Brush)GetValue(MouseOverColorProperty); }
                set { SetValue(MouseOverColorProperty, value); }
            }
    
            public RadioButton360()
            {
                try
                {
                    this.Resources.Source = new Uri("DialogEx;Component/Controls/RadioButton360.xaml", UriKind.RelativeOrAbsolute);
                }
                catch
                {
                    throw new Exception("未找到:DialogEx;Component/Controls/RadioButton360.xaml");
                }
            }
            private static void PropertyChanged(DependencyObject dobj, DependencyPropertyChangedEventArgs e)
            {
                RadioButton360 control = (RadioButton360)dobj;
                control.Resources["CheckedColor"] = control.CheckedColor;
                control.Resources["UnCheckedColor"] = control.UnCheckedColor;
                control.Resources["MouseOverColor"] = control.MouseOverColor;
                control.Style = control.Resources["RadioButtonStyle"] as Style;
                //String.Format("PropertyChanged - 属性:{0} 新值:{1} 旧值:{2}", e.Property.Name, e.NewValue, e.OldValue);
            }

    PropertyChanged 这个函数就是用来在通知之后执行的。这样我们可以在自定义控件初始化的时候加载资源,当依赖属性发生变化时,会触发事件,

    我们回调至这个函数就能达到效果。结果将会界面上实时显示



    经过测试!上面这种方法不安全。不知道什么问题造成的。初始值经常会覆盖设置的值。不知道有没有人有办法彻底解决。

    展开全文
  • 自定义一个简单控件,添加依赖属性,想在xmal中绑定设置依赖属性的值,绑定不起作用求问是怎么回事? ``` public partial class LabelEx : UserControl { public LabelEx() { InitializeComponent();...
  • dp dp DependencyProperty的代码片段 wp Expansion classname 类名 ClassName() ClassNamePlaceholder type 属性类型 int property 属性名 MyProperty wpdp 依赖属性名 MyDependencyProperty public $type$ $...
    <?xml version="1.0" encoding="utf-8"?>
    <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    	<CodeSnippet Format="1.0.0">
    		<Header>
    			<Title>dp</Title>
    			<Shortcut>dp</Shortcut>
    			<Description>DependencyProperty的代码片段</Description>
    			<Author>wp</Author>
    			<SnippetTypes>
    				<SnippetType>Expansion</SnippetType>
    			</SnippetTypes>
    		</Header>
    		<Snippet>
    			<Declarations>
    				<Literal Editable="false">
    					<ID>classname</ID>
    					<ToolTip>类名</ToolTip>
    					<Function>ClassName()</Function>
    					<Default>ClassNamePlaceholder</Default>
    				</Literal>
    				<Literal>
    					<ID>type</ID>
    					<ToolTip>属性类型</ToolTip>
    					<Default>int</Default>
    				</Literal>
    				<Literal>
    					<ID>property</ID>
    					<ToolTip>属性名</ToolTip>
    					<Default>MyProperty</Default>
    				</Literal>
    				<Literal>
    					<ID>wpdp</ID>
    					<ToolTip>依赖属性名</ToolTip>
    					<Default>MyDependencyProperty</Default>
    				</Literal>
    			</Declarations>
    			<Code Language="csharp"><![CDATA[ public $type$ $property$
            {
                get => ($type$)GetValue($wpdp$);
                set => SetValue($wpdp$, value);
            }
    
            public static readonly DependencyProperty $wpdp$
                = DependencyProperty.Register(nameof($property$), typeof($type$), typeof($classname$), new PropertyMetadata(default($type$)));$end$]]>
    			</Code>
    		</Snippet>
    	</CodeSnippet>
    </CodeSnippets>

     

    展开全文
  • 控件cs文件 using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Markup; using System.Windows.Media; ...

    控件cs文件

    using System.ComponentModel;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Controls.Primitives;
    using System.Windows.Markup;
    using System.Windows.Media;
    
    namespace Controls
    {
    
        [TemplatePart(Name = "PART_DropDown", Type = typeof(System.Windows.Controls.Button))]
        [ContentProperty("Items")]
        [DefaultProperty("Items")]
        public class MyButton: System.Windows.Controls.Button
        {
            public static readonly DependencyProperty HorizontalOffsetProperty;
            public static readonly DependencyProperty IsContextMenuOpenProperty;
            public static readonly DependencyProperty ModeProperty;
            public static readonly DependencyProperty PlacementProperty;
            public static readonly DependencyProperty PlacementRectangleProperty;
            public static readonly DependencyProperty VerticalOffsetProperty;
    
            public static readonly DependencyProperty ImageSourceProperty =
                  DependencyProperty.Register("ImageSource", typeof(string), typeof(MyButton), new PropertyMetadata(""));
            public static readonly DependencyProperty ImageSourceChangeProperty =
                  DependencyProperty.Register("ImageSourceChange", typeof(string), typeof(MyButton), new PropertyMetadata(""));
    
    /// <summary>
            /// Static Constructor
            /// </summary>
            static MyButton()
            {
                DefaultStyleKeyProperty.OverrideMetadata(typeof(MyButton), new FrameworkPropertyMetadata(typeof(MyButton)));
                IsContextMenuOpenProperty = DependencyProperty.Register("IsContextMenuOpen", typeof(bool), typeof(MyButton), new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnIsContextMenuOpenChanged)));
                ModeProperty = DependencyProperty.Register("Mode", typeof(MyButtonMode), typeof(MyButton), new FrameworkPropertyMetadata(MyButtonMode.Split));
    
    
                PlacementProperty = ContextMenuService.PlacementProperty.AddOwner(typeof(MyButton), new FrameworkPropertyMetadata(PlacementMode.Bottom, new PropertyChangedCallback(OnPlacementChanged)));
                PlacementRectangleProperty = ContextMenuService.PlacementRectangleProperty.AddOwner(typeof(MyButton), new FrameworkPropertyMetadata(Rect.Empty, new PropertyChangedCallback(OnPlacementRectangleChanged)));
                HorizontalOffsetProperty = ContextMenuService.HorizontalOffsetProperty.AddOwner(typeof(MyButton), new FrameworkPropertyMetadata(0.0, new PropertyChangedCallback(OnHorizontalOffsetChanged)));
                VerticalOffsetProperty = ContextMenuService.VerticalOffsetProperty.AddOwner(typeof(MyButton), new FrameworkPropertyMetadata(0.0, new PropertyChangedCallback(OnVerticalOffsetChanged)));
            }
    
    
            /*
             * Overrides
             * 
            */
            /// <summary>
            /// OnApplyTemplate override, set up the click event for the dropdown if present in the template
            /// </summary>
            public override void OnApplyTemplate()
            {
                base.OnApplyTemplate();
    
                // set up the click event handler for the dropdown button
                System.Windows.Controls.Primitives.ButtonBase dropDown = this.Template.FindName("PART_DropDown", this) as System.Windows.Controls.Primitives.ButtonBase;
                if (dropDown != null)
                    dropDown.Click += Dropdown_Click;
            }
    
            /// <summary>
            ///     Handles the Base Buttons OnClick event
            /// </summary>
            protected override void OnClick()
            {
                switch (Mode)
                {
                    case MyButtonMode.Dropdown:
                        OnDropdown();
                        break;
    
                    default:
                        base.OnClick(); // forward on the Click event to the user
                        break;
                }
            }
    
            /*
             * Properties
             * 
            */
    
    
            /// <summary>
            /// The Split Button's Items property maps to the base classes ContextMenu.Items property
            /// </summary>
            public ItemCollection Items
            {
                get
                {
                    EnsureContextMenuIsValid();
                    return this.ContextMenu.Items;
                }
            }
    
            /*
             * DependencyProperty CLR wrappers
             * 
            */
    
            public string ImageSource
            {
                get { return (string)GetValue(ImageSourceProperty); }
                set { SetValue(ImageSourceProperty, value); }
            }
    
            public string ImageSourceChange
            {
                get { return (string)GetValue(ImageSourceChangeProperty); }
                set { SetValue(ImageSourceChangeProperty, value); }
            }
    
    /// <summary>
            /// Gets or sets the IsContextMenuOpen property. 
            /// </summary>
            public bool IsContextMenuOpen
            {
                get { return (bool)GetValue(IsContextMenuOpenProperty); }
                set { SetValue(IsContextMenuOpenProperty, value); }
            }
    
    
            /// <summary>
            /// Placement of the Context menu
            /// </summary>
            public PlacementMode Placement
            {
                get { return (PlacementMode)GetValue(PlacementProperty); }
                set { SetValue(PlacementProperty, value); }
            }
    
    
            /// <summary>
            /// PlacementRectangle of the Context menu
            /// </summary>
            public Rect PlacementRectangle
            {
                get { return (Rect)GetValue(PlacementRectangleProperty); }
                set { SetValue(PlacementRectangleProperty, value); }
            }
    
    
            /// <summary>
            /// HorizontalOffset of the Context menu
            /// </summary>
            public double HorizontalOffset
            {
                get { return (double)GetValue(HorizontalOffsetProperty); }
                set { SetValue(HorizontalOffsetProperty, value); }
            }
    
    
            /// <summary>
            /// VerticalOffset of the Context menu
            /// </summary>
            public double VerticalOffset
            {
                get { return (double)GetValue(VerticalOffsetProperty); }
                set { SetValue(VerticalOffsetProperty, value); }
            }
    
            /// <summary>
            /// Defines the Mode of operation of the Button
            /// </summary>
            /// <remarks>
            ///     The MyButton two Modes are
            ///     Split (default),    - the button has two parts, a normal button and a dropdown which exposes the ContextMenu
            ///     Dropdown            - the button acts like a combobox, clicking anywhere on the button opens the Context Menu
            /// </remarks>
            public MyButtonMode Mode
            {
                get { return (MyButtonMode)GetValue(ModeProperty); }
                set { SetValue(ModeProperty, value); }
            }
    
            /*
             * DependencyPropertyChanged callbacks
             * 
            */
    
            private static void OnIsContextMenuOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                MyButton s = (MyButton)d;
                s.EnsureContextMenuIsValid();
    
                if (!s.ContextMenu.HasItems)
                    return;
    
                bool value = (bool)e.NewValue;
    
                if (value && !s.ContextMenu.IsOpen)
                    s.ContextMenu.IsOpen = true;
                else if (!value && s.ContextMenu.IsOpen)
                    s.ContextMenu.IsOpen = false;
            }
    
    
            /// <summary>
            /// Placement Property changed callback, pass the value through to the buttons context menu
            /// </summary>
            private static void OnPlacementChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                MyButton s = d as MyButton;
                if (s == null) return;
    
                s.EnsureContextMenuIsValid();
                s.ContextMenu.Placement = (PlacementMode)e.NewValue;
            }
    
            /// <summary>
            /// PlacementRectangle Property changed callback, pass the value through to the buttons context menu
            /// </summary>
            private static void OnPlacementRectangleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                MyButton s = d as MyButton;
                if (s == null) return;
    
                s.EnsureContextMenuIsValid();
                s.ContextMenu.PlacementRectangle = (Rect)e.NewValue;
            }
    
            /// <summary>
            /// HorizontalOffset Property changed callback, pass the value through to the buttons context menu
            /// </summary>
            private static void OnHorizontalOffsetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                MyButton s = d as MyButton;
                if (s == null) return;
    
                s.EnsureContextMenuIsValid();
                s.ContextMenu.HorizontalOffset = (double)e.NewValue;
            }
    
            /// <summary>
            /// VerticalOffset Property changed callback, pass the value through to the buttons context menu
            /// </summary>
            private static void OnVerticalOffsetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                MyButton s = d as MyButton;
                if (s == null) return;
    
                s.EnsureContextMenuIsValid();
                s.ContextMenu.VerticalOffset = (double)e.NewValue;
            }
    
            /*
             * Helper Methods
             * 
            */
    
            /// <summary>
            /// Make sure the Context menu is not null
            /// </summary>
            private void EnsureContextMenuIsValid()
            {
                if (this.ContextMenu == null)
                {
                    this.ContextMenu = new System.Windows.Controls.ContextMenu();
                    this.ContextMenu.PlacementTarget = this;
                    this.ContextMenu.Placement = Placement;
    
                    this.ContextMenu.Opened += ((sender, routedEventArgs) => IsContextMenuOpen = true);
                    this.ContextMenu.Closed += ((sender, routedEventArgs) => IsContextMenuOpen = false);
                }
            }
    
            private void OnDropdown()
            {
                EnsureContextMenuIsValid();
                if (!this.ContextMenu.HasItems)
                    return;
    
                this.ContextMenu.IsOpen = !IsContextMenuOpen; // open it if closed, close it if open
            }
    
            /*
             * Events
             * 
            */
    
            /// <summary>
            /// Event Handler for the Drop Down Button's Click event
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void Dropdown_Click(object sender, RoutedEventArgs e)
            {
                OnDropdown();
                e.Handled = true;
            }
        }
    }

     

    控件xaml

    <ResourceDictionary
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:comm="clr-namespace:Controls">
    
        <Style x:Key="ButtonFocusVisual">
            <Setter Property="Control.Template">
                <Setter.Value>
                    <ControlTemplate>
                        <Rectangle
                            Margin="3"
                            SnapsToDevicePixels="true"
                            Stroke="Transparent"
                            StrokeDashArray="1 2"
                            StrokeThickness="1" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style TargetType="Button">
            <Setter Property="Foreground" Value="#D5D5D5" />
            <Setter Property="FontSize" Value="13" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Image
                            x:Name="image"
                            HorizontalAlignment="Center"
                            VerticalAlignment="Center"
                            Source="{Binding Path=ImageSource, RelativeSource={RelativeSource AncestorType={x:Type comm:MyButton}}}" />
    
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter TargetName="image" Property="Source" Value="{Binding Path=ImageSourceChange, RelativeSource={RelativeSource AncestorType={x:Type comm:MyButton}}}" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style TargetType="{x:Type comm:MyButton}">
            <Setter Property="FocusVisualStyle" Value="{StaticResource ButtonFocusVisual}" />
            <Setter Property="FontSize" Value="13" />
            <Setter Property="Foreground" Value="#D5D5D5" />
            <Setter Property="FontFamily" Value="微软雅黑" />
            <Setter Property="HorizontalContentAlignment" Value="Center" />
            <Setter Property="VerticalContentAlignment" Value="Center" />
            <Setter Property="Padding" Value="0" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type comm:MyButton}">
                        <Border
                            x:Name="grid"
                            HorizontalAlignment="Stretch"
                            VerticalAlignment="Stretch"
                            Background="Transparent"
                            CornerRadius="4">
    
                            <Button x:Name="PART_DropDown" />
                        </Border>
                        <ControlTemplate.Triggers>
    
    
                            <Trigger SourceName="PART_DropDown" Property="IsMouseOver" Value="true">
                                <Setter TargetName="PART_DropDown" Property="Opacity" Value="1" />
                                <Setter TargetName="grid" Property="Background" Value="Transparent" />
                            </Trigger>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter Property="Foreground" Value="#ADADAD" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ResourceDictionary>

     

    页面使用:

    <comm:MyButton
                        Width="38"
                        Height="40"
                        ImageSource="/control;component/Icons/picture2.png"
                        ImageSourceChange="/control;component/Icons/picture1.png">
    
                    </comm:MyButton>

     

    转载于:https://www.cnblogs.com/amwuau/p/7561570.html

    展开全文
  • 针对自定义控件的特性,由于它的界面是在一个Themes/Generic.xaml文件中,并且在ControlTemplate中,所以,不能根据x:Name来访问其中的控件,在ControlTemplate中的资源和控件(建议把资源和控件,动画等都写到...

    针对自定义控件的特性,由于它的界面是在一个Themes/Generic.xaml文件中,并且在ControlTemplate中,所以,不能根据x:Name来访问其中的控件,在ControlTemplate中的资源和控件(建议把资源和控件,动画等都写到ControlTemplate中)的访问要通过重写OnApplyTemplate,方法GetTemplateChild来获得。

    那么,许多特性就不能在xaml中编写了,包括绑定。

    自定义控件,依赖属性如何绑定到Generic.xaml中的控件上,只能通过GetTemplateChild方法获取到该控件,然后在后台绑定。动画可以写到资源中,到时候获取然后Begin即可,但是不建议这么做,因为考虑到灵活性,动画的值如果跟业务相关那就不好控制了,所以建议在后台创建动画,虽然代码比较多,但是灵活。

    在创建依赖属性时

    public static DependencyProperty Register(
        string name,
        Type propertyType,
        Type ownerType,
        PropertyMetadata defaultMetadata
    )

    注意到第四个参数PropertyMetadata,该参数不仅能赋给一个默认值,还能够添加一个函数,该函数将在依赖属性值改变的时候执行,我们的动画Begin就在这里面,但是该方法是静态的又该怎么弄?

    请看代码

    public float CurrentValue
            {
                get { return (float)GetValue(CurrentValueProperty); }
                set { SetValue(CurrentValueProperty, value); }
            }
    
            // Using a DependencyProperty as the backing store for CurrentValue.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty CurrentValueProperty =
                DependencyProperty.Register("CurrentValue", typeof(float), typeof(Temp), new PropertyMetadata(50f, CurrentValueChange));
    
            public static void CurrentValueChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                (d as Temp).StoryboardPlay(e);
            }
    
            protected void StoryboardPlay(DependencyPropertyChangedEventArgs e)
            {
                Storyboard sb = new Storyboard();
                DoubleAnimation da = new DoubleAnimation();
                da.To = double.Parse(e.NewValue.ToString());
                da.Duration = new Duration(TimeSpan.Parse("0:0:1"));
                rect.BeginAnimation(Rectangle.HeightProperty, da);
            }

    这样就完美解决问题了。

    源码在这http://files.cnblogs.com/HelloMyWorld/%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8E%A7%E4%BB%B6%E5%BC%80%E5%8F%91Sample.zip

    转载于:https://www.cnblogs.com/HelloMyWorld/archive/2013/04/05/3001154.html

    展开全文
  • VB.NET做的一个WPF的Demo,做了个控件。像是Windows图标一样.图片加文字,移动到图片上,图片会放大。这个demo也说明了如何建立一个自定义属性,并把UserControl中的控件属性绑定到自己定义的属性中。
  • 由于刚接触WPF不久,经验不足,走了很多弯路,比如本次遇到的设置自定义控件依赖属性无效问题,该依赖属性没有在自定义控件前台直接使用,只是作为一个标识通过后端代码来控制前端部分控件,依赖属性定义看起来没啥问题,...
  • 这篇文章的意义是,为wpf自定义控件,定义它的专属属性,这个属性不仅仅可以在c#中使用,也可以在xaml中使用,在xaml中赋值或者绑定。 在wpf开发过程中,总会用到格式各样的控件,但是原生控件远远不能满足实际...
  • WPF 自定义控件依赖属性的简单使用 一、首先添加一个简单自定义控件UserTestControl; xaml代码如下,将背景色绑定依赖属性: <UserControl x:Class="WpfApp1.UserTestControl" xmlns=...
  • WPF自定义控件中如果需要开放属性,则定义依赖属性 步骤1:在cs文件中通过快捷键,新增依赖属性 步骤二: 在Generic中绑定模板属性 第三步骤: 使用属性 第二部分: 公开事件 在设置依赖项...
  • 原先控件依赖属性写法如下 public class MyControl : Control { public double MyWidth { get => (double)GetValue(MyWidthProperty); set => SetValue(MyWidthProperty, ...
  • 首先一些人觉得WPF中前台的代码应该在前台创建,尽量不要在后台用代码创建。另外如果前台重复代码过多,编写起来非常繁琐而且修改更是头痛。因此使用用户控件的方法把经常使用的前台模块制作成控件,当然用法和普通...
  • WPF自定义控件的自定义属性绑定后不更新问题 原文:WPF自定义控件的自定义属性绑定后不更新问题 需要在绑定时设置属性变更触发 UpdateSourceTrigger=...
  • 在UserControl里放入一个TreeView,需要 依赖属性ItemsSource 和 路由事件SelectedItemChanged 参考: http://www.cnblogs.com/zhouyinhui/archive/2007/10/27/939920.html   以下是我的部分代码 ...
  • WPF自定义控件创建

    2021-04-08 06:22:24
    WPF自定义控件创建 本文简单的介绍一下WPF自定义控件的开发。 首先,我们打开VisualStudio创建一个WPF自定义控件库,如下图: 然后,我们可以看到创建的解决方案如下: 在解决方案中,我们看到了一个Themes文件夹...
  • Padding="5" /> </Grid> <Grid Grid.Column="1"> ,Mode=TwoWay}" TurnMinValue="0" TurnMaxValue="80" Width="Auto" Height="Auto" x:Name="FTVB" /> </Grid> </Grid> 问题:自定义控件依赖属性再绑定viewmodel...
  • [WPF自定义控件]从ContentControl开始入门自定义控件 原文:[WPF自定义控件]从ContentControl开始入门自定义控件1. 前言 我去年写过一个在UWP自定义控件的系列博客,大部分的经验都可以用在WPF中...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 4,266
精华内容 1,706
关键字:

wpf自定义控件依赖属性