自定义控件模板,不用依赖属性---------------------WPF

我觉得用依赖属性的方法来写个控件模板,看起来太乱,不好看。。所以,在网上无意中找到了一个给资源文件定义一个类的方法

1.资源文件中

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    x:Class="WpfApplication1.Class1"
                    >
               <!--注意这个x:Class-->
    <ControlTemplate x:Key="Mbutton2" TargetType="Button">
        <Border Height="30" Width="50" Margin="10,0,0,0" >
            <Button x:Name="woshini" x:Uid="woshini"  Content="nihao"  Click="nihaos"></Button>
        </Border>
    </ControlTemplate>
</ResourceDictionary>

2.后台类

namespace WpfApplication1
{
    //这里必须是有partial
    partial class Class1 : ResourceDictionary
    {

      private static void NormalBrushChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
      {
          Button ditem = d as Button;
          ditem.OnApplyTemplate();
      }
        public Class1()
        {
            InitializeComponent();
          
            int i = 0;
        }
        public void nihaos(object sender, RoutedEventArgs e)
        {            //省去处理,如果显示,表明调用成功。      
            MessageBox.Show("你成功了!");
            Button bt = sender as Button;
         
           
        }
    }
}

3.页面调用

  <Window.Resources>
        <!--还是得引用-->
        <ResourceDictionary >
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/WpfApplication1;component/Dictionary1.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>

    </Window.Resources>
    <Grid>
        <Button Template="{StaticResource Mbutton2}"></Button>
    </Grid>

这样就可以完成了。但是有个比较麻烦的问题,,我想获取模板中某个控件的实例对象的时候不能主动的去获取。。。只能等那个对象触发某个事件的时候我才能记下这个控件,和控件的对象

posted on 2015-11-19 15:03  你的乐哥哥  阅读(1302)  评论(0编辑  收藏  举报