WPF用戶控件入門

最近在學習WPF,發現很多優秀的用戶界面都有用到用戶控件,學習一下簡單的使用方法。用戶控件就像一件出租房,自己裝修,出租給用戶讓用戶自己隨意使用,但是需要簽訂租房合同來維護各自的權益。

1、創建一個簡單的用戶控件包含一個Textbox和一個Button。

<UserControl x:Class="Test.UserControl1"
             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:Test"
             mc:Ignorable="d" 
             d:DesignHeight="100" d:DesignWidth="200">
    <Grid Margin="0,0,0,0">
        <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="10,10,10,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="198" />
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="10,46,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>

    </Grid>
</UserControl>
2、公佈Button的Click事件,讓用戶可以在按鈕事件裏做自己想做的事。
<pre name="code" class="csharp">public partial class UserControl1 : UserControl
    {
        public event RoutedEventHandler ClickButton;

        public UserControl1()
        {
            InitializeComponent();
        }

        public void button_Click(object sender, RoutedEventArgs e)
        {
            if (ClickButton != null)
                ClickButton(sender, e);
        }
    }
3、使用用戶控件。
<pre name="code" class="html"><Window x:Class="test.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:test"
        xmlns:WinFormHost="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
        xmlns:WinFormControls="clr-namespace:Emgu.CV.UI;assembly=Emgu.CV.UI"  
        mc:Ignorable="d"
        Title="test" Height="600" Width="800">
    <Grid ShowGridLines="True" Margin="0,10,0,0" x:Name="gridForm">
        <local:UserControl1 x:Name="uc1" />
    </Grid>
</Window>

  public MainWindow()
        {
            InitializeComponent();
            uc1.ClickButton += new RoutedEventHandler(uc_ClickButton);
        }

        private void uc_ClickButton(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(uc1.textBox.Text);
        }


4、很簡單淺顯的例子,供自己複習參考用。





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章