zoukankan      html  css  js  c++  java
  • WPF ----在UserControl的xaml里绑定依赖属性

    场景:在定义wpf 用户控件的时候,希望使用时设置自定义的属性来改变用户控件里的状态或内容等。

    下面直接上实例代码:

    用户控件的后台代码,定义依赖属性

       public partial class MyUserControl : UserControl
        {
            public MyUserControl()
            {
                InitializeComponent();
            }
    
    
    
            public string MyProperty
            {
                get { return (string)GetValue(MyPropertyProperty); }
                set { SetValue(MyPropertyProperty, value); }
            }
    
            // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty MyPropertyProperty =
                DependencyProperty.Register("MyProperty", typeof(string), typeof(MyUserControl), new PropertyMetadata(""));
    
            
    
        }
    }

    Xaml 代码中绑定依赖属性 

    <UserControl x:Class="WPFTest.MyUserControl"
                 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:myCtl="clr-namespace:WPFTest"
                 d:DesignHeight="300"
                 d:DesignWidth="300"
                 mc:Ignorable="d">
        <StackPanel>
            <TextBlock Text="{Binding RelativeSource={RelativeSource   Mode= FindAncestor,  AncestorType={x:Type myCtl:MyUserControl}}, Path=MyProperty}" />
        </StackPanel>
    </UserControl>

    下面是自定义控件的使用实例:

    <Window x:Class="WPFTest.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:WPFTest="clr-namespace:WPFTest"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            Title="MainWindow"
            Width="525"
            Height="350"
            mc:Ignorable="d">
        <Grid>
            <WPFTest:MyUserControl MyProperty="ddd" />
        </Grid>
    </Window>

    希望对大家有用!

  • 相关阅读:
    洛谷1076 寻宝
    洛谷1349 广义斐波那契数列 【矩阵乘法】
    BZOJ1008 [HNOI2008]越狱
    vijosP1629 八
    vijosP1687 细菌总数
    vijosP1388 二叉树数
    怎么在windows上安装 ansible How to install ansible to my python at Windows
    阿里邮箱绑定Foxmail失败的解决办法
    Django html页面 'ascii' codec can't encode characters in position 8-10: ordinal not
    python2.X现在不能安装Django了:Collecting django Using cached Django-2.0.tar.gz
  • 原文地址:https://www.cnblogs.com/karl-F/p/6517953.html
Copyright © 2011-2022 走看看