WPF基础

数据绑定模式共有四种:OneTime、OneWay、OneWayToSource和TwoWay,默认是TwoWay。

TwoWay 当发生更改时的目标属性或源属性更新目标属性。
OneWay 仅当源属性更改时,请更新目标属性。
OneTime 仅当应用程序启动时或时,请更新目标属性DataContext发生了更改。
OneWayToSource 目标属性更改时,请更新源属性。

  1. 实现INotifyPropertyChanged并通过OnPropertyChanged主动更新绑定的控件
 public class BindEx : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;


        protected internal virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
  1. 构造model
 public class testModel : BindEx
    {
        private string _test="";
        public string test
        {
            get
            {
                return _test;
            }
            set
            {
                _test = value;
                OnPropertyChanged("test");
            }
        }
    }
  1. 绑定数据
        <TextBox Text="{Binding test}"/>

 model = new testModel
            {
                test = "test"
            };
            this.DataContext = model;
  1. 后台绑定样式
//后台设置绑定的资源
control.style=Resources["MyButton"] as style
  1. 绑定指定类型数据
xmlns:sys="clr-namespace:System;assembly=mscorlib"

<cvt:EqualVisibilityConverter x:Key="equalVisibilityConverter"/>


 <Image.Visibility>
	<Binding Path="IsEnable"  Converter="{StaticResource equalVisibilityConverter}">
		<Binding.ConverterParameter>
			<sys:Boolean>true</sys:Boolean>
		</Binding.ConverterParameter>
	</Binding>
</Image.Visibility>

6.触发自定义事件 模拟点击

Button btn=new Button();
btn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, btn));

Image img = new Image();
img.RaiseEvent(new RoutedEventArgs(Image.MouseLeftButtonDownEvent, img));
  1. 按钮禁用时显示tooltip
ToolTipService.ShowOnDisabled="True"
  1. dastagrid拉伸
    设置ColumnWidth="" 同时保证设置column宽度为

  2. 捕获鼠标
    捕获后即使移动到窗口外依然可以捕获鼠标事件

((UIElement)e.Source).CaptureMouse();

  1. 设计时约定viewmodel类型
    通过d:DataContext设置设计时上下文类型
    运行时通过mc:Ignorable="d" 忽略此设置
<Window x:Class="MagicDrawingTool.MainWindow"
        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:local="clr-namespace:MagicDrawingTool"
        xmlns:vm="clr-namespace:MagicDrawingTool.VM"
        d:DataContext="{d:DesignInstance Type=vm:VMMain}"
        mc:Ignorable="d" 
        Title="MainWindow" Height="450" Width="800">
    <Grid>
    </Grid>
</Window>

  1. 前台设置上下文
    通过<UserControl.DataContext>设置上下文,初始化后会自动创建上下文对象,而无需在后台绑定
<UserControl x:Class="RDTool.UserControls.ConsulControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:RDTool.UserControls" 
             xmlns:viewmodel="clr-namespace:RDTool.ViewModel.Consul" xmlns:hc="https://handyorg.github.io/handycontrol"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <UserControl.DataContext>
        <viewmodel:VMConsul/>
    </UserControl.DataContext>
    <Grid>
    </Grid>
</UserControl>


  1. 同步上下文 - 后台操作前台界面
  System.Threading.SynchronizationContext.Current.Post((_) =>
            {
                //更新界面
            }, null);
  1. FrameworkElement.FindName
//通过元素获取子元素
checkBox1.FindName("PART_ContentPresenter");

//根据类型获取
page.FindVisualChild<ComboBox>();
  1. 可视化树
ublic static class VisualTreeHelpers
{
    private static T FindVisualChild<T>(this DependencyObject dependencyObject, string name) where T : DependencyObject
    {
        int childrenCount = VisualTreeHelper.GetChildrenCount(dependencyObject);
        if (childrenCount == 0 && dependencyObject is Popup)
        {
            UIElement child = (dependencyObject as Popup).Child;
            if (child == null)
            {
                return null;
            }

            return child.FindVisualChild<T>(name);
        }

        for (int i = 0; i < childrenCount; i++)
        {
            DependencyObject child2 = VisualTreeHelper.GetChild(dependencyObject, i);
            string text = child2.GetValue(FrameworkElement.NameProperty) as string;
            if (child2 is T && (name == string.Empty || name == text))
            {
                return (T)child2;
            }

            T val = child2.FindVisualChild<T>(name);
            if (val != null)
            {
                return val;
            }
        }

        return null;
    }

    private static IEnumerable<T> GetChildrenOf<T>(this DependencyObject obj, bool recursive) where T : DependencyObject
    {
        int count = VisualTreeHelper.GetChildrenCount(obj);
        for (int i = 0; i < count; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(obj, i);
            if (child is T)
            {
                yield return (T)child;
            }

            if (!recursive)
            {
                continue;
            }

            foreach (T item in child.GetChildrenOf<T>())
            {
                yield return item;
            }
        }
    }

    private static IEnumerable<T> GetChildrenOf<T>(this DependencyObject obj) where T : DependencyObject
    {
        return obj.GetChildrenOf<T>(recursive: false);
    }

    private static DependencyObject GetParentObject(this DependencyObject child)
    {
        if (child == null)
        {
            return null;
        }

        if (child is ContentElement contentElement)
        {
            DependencyObject parent = ContentOperations.GetParent(contentElement);
            if (parent != null)
            {
                return parent;
            }

            return (contentElement as FrameworkContentElement)?.Parent;
        }

        if (child is FrameworkElement frameworkElement)
        {
            DependencyObject parent2 = frameworkElement.Parent;
            if (parent2 != null)
            {
                return parent2;
            }
        }

        return VisualTreeHelper.GetParent(child);
    }

    public static T FindAncestor<T>(DependencyObject current) where T : DependencyObject
    {
        for (current = VisualTreeHelper.GetParent(current); current != null; current = VisualTreeHelper.GetParent(current))
        {
            if (current is T)
            {
                return (T)current;
            }
        }

        return null;
    }

    public static T FindAncestor<T>(DependencyObject current, T lookupItem) where T : DependencyObject
    {
        while (current != null)
        {
            if (current is T && current == lookupItem)
            {
                return (T)current;
            }

            current = VisualTreeHelper.GetParent(current);
        }

        return null;
    }

    public static T FindAncestor<T>(DependencyObject current, string parentName) where T : DependencyObject
    {
        while (current != null)
        {
            if (!string.IsNullOrEmpty(parentName))
            {
                FrameworkElement frameworkElement = current as FrameworkElement;
                if (current is T && frameworkElement != null && frameworkElement.Name == parentName)
                {
                    return (T)current;
                }
            }
            else if (current is T)
            {
                return (T)current;
            }

            current = VisualTreeHelper.GetParent(current);
        }

        return null;
    }

    public static T FindChild<T>(DependencyObject parent, string childName) where T : DependencyObject
    {
        if (parent == null)
        {
            return null;
        }

        T val = null;
        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(parent, i);
            if (child as T == null)
            {
                val = FindChild<T>(child, childName);
                if (val != null)
                {
                    break;
                }

                continue;
            }

            if (!string.IsNullOrEmpty(childName))
            {
                if (child is FrameworkElement frameworkElement && frameworkElement.Name == childName)
                {
                    val = (T)child;
                    break;
                }

                val = FindChild<T>(child, childName);
                if (val != null)
                {
                    break;
                }

                continue;
            }

            val = (T)child;
            break;
        }

        return val;
    }

    public static T FindChild<T>(DependencyObject parent) where T : DependencyObject
    {
        if (parent == null)
        {
            return null;
        }

        T val = null;
        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(parent, i);
            if (child as T == null)
            {
                val = FindChild<T>(child);
                if (val != null)
                {
                    break;
                }

                continue;
            }

            val = (T)child;
            break;
        }

        return val;
    }

    public static T FindVisualChild<T>(this DependencyObject dependencyObject) where T : DependencyObject
    {
        return dependencyObject.FindVisualChild<T>(string.Empty);
    }

    public static Visual GetDescendantByType(Visual element, Type type)
    {
        if (element == null)
        {
            return null;
        }

        if (element.GetType() == type)
        {
            return element;
        }

        Visual visual = null;
        if (element is FrameworkElement frameworkElement)
        {
            frameworkElement.ApplyTemplate();
        }

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
        {
            visual = GetDescendantByType(VisualTreeHelper.GetChild(element, i) as Visual, type);
            if (visual != null)
            {
                break;
            }
        }

        return visual;
    }

    public static DataGridColumnHeader GetHeader(DataGridColumn column, DependencyObject reference)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(reference); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(reference, i);
            if (child is DataGridColumnHeader dataGridColumnHeader && dataGridColumnHeader.Column == column)
            {
                return dataGridColumnHeader;
            }

            DataGridColumnHeader header = GetHeader(column, child);
            if (header != null)
            {
                return header;
            }
        }

        return null;
    }

    public static T TryFindParent<T>(this DependencyObject child) where T : DependencyObject
    {
        DependencyObject parentObject = child.GetParentObject();
        if (parentObject == null)
        {
            return null;
        }

        if (parentObject is T result)
        {
            return result;
        }

        return parentObject.TryFindParent<T>();
    }
}
  1. Messenger - MVVM Light
Messenger.Default.Register<string>(this, "TestToken", GetData);
Messenger.Default.Send(new NotificationMessage("MessageContent"));

  1. 窗口自适应内容大小
// Manually alter window height and width
this.SizeToContent = SizeToContent.Manual;

// Automatically resize width relative to content
this.SizeToContent = SizeToContent.Width;

// Automatically resize height relative to content
this.SizeToContent = SizeToContent.Height;

// Automatically resize height and width relative to content
this.SizeToContent = SizeToContent.WidthAndHeight;
posted @ 2021-01-01 16:49  Hey,Coder!  阅读(447)  评论(0)    收藏  举报