【demo练习二】:WPF依赖属性的练习

2016-10-11

依赖属性demo小样:

要求:在窗口中点击按钮,利用设置“依赖属性”把LabelTextBox控件里的属性值进行改变。

=====================================================

MainWindow.xaml代码:

<Window x:Class="依赖属性1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
  <Canvas Width="1024" Height="768">
    <Label x:Name="label" Content="Label" HorizontalAlignment="Center" VerticalAlignment="Center" Canvas.Left="71" Canvas.Top="77" Background="Yellow"/>
    <Button x:Name="button" Content="点击转换" Background="SkyBlue" Canvas.Left="83" Canvas.Top="188" Width="68" Click="button_Click" />
    <TextBox x:Name="textbox1" Width="120" Height="30" Canvas.Left="180" Canvas.Top="70" Text="12345678"/>
    <TextBox x:Name="textbox2" Width="120" Height="30" Canvas.Left="180" Canvas.Top="180" />
  </Canvas>
</Window>

====================================================

MainWindow.xaml.cs代码

//设置依赖属性
public static DependencyProperty TextProperty = DependencyProperty.Register(

  "Text",
  typeof(string),
  typeof(MainWindow),
  new PropertyMetadata("",PropertyChanged)
  );

public string Text
{
  get { return (string)GetValue(TextProperty); }
  set { SetValue(TextProperty, value); }
}

private static void PropertyChanged(DependencyObject dobj,DependencyPropertyChangedEventArgs e)
{
  MainWindow control = (MainWindow)dobj;
  if (control != null)
  {
    if (control.Text == "1")
    {
      control.label.Content = "YNWA!";
      control.label.FontSize = 10;
      control.textbox1.Text = "This is anfield!";
    }
    else if(control.Text == "2")
    {
      control.label.Content = "Make The Dream!";
      control.label.FontSize = 10;
      control.textbox1.Text = "This is tianjin anfield!";
    }
  }
}

private void button_Click(object sender, RoutedEventArgs e)
{
  this.Text = this.textbox2.Text;
}

posted @ 2016-10-11 15:35  Owen_ET  阅读(366)  评论(0编辑  收藏  举报