الاثنين، 30 مايو 2011

WPF User Control

The role that user controls and custom controls play in WPF is quite different than in other technologies. In other technologies, custom controls are often created simply to get a nonstandard look. But WPF has many options for achieving nonstandard-looking controls without creating brand-new controls. You can completely restyle built-in controls with WPF’s style and template mechanisms. Or you can sometimes simply embed complex content inside built-in controls to get the look you want.
In other technologies, a Button containing an Image or a TreeView containing ComboBoxes might necessitate a custom control, but not in WPF! (That’s not to say that there are fewer opportunities for selling reusable components. It just means you’ve got more implementation options.
Therefore, the decision to create a user control or custom control should be based on the APIs you want to expose rather than the look you want to achieve. If no existing control has a programmatic interface that naturally represents your concept, go ahead and create a user control or custom control. The biggest mistake people make with user controls and custom controls is creating one from scratch when an existing one can suffice.


Steps
1-      Add new Item > Add User control
2-      We want to make file browse control > add textbox   and Button control
      <DockPanel>
            <Button x:Name="theButton" DockPanel.Dock="Right" Height="45" Width="74">
                Browse...Button>
            <TextBox x:Name="theTextBox" Background="Yellow"  Height="37" Width="200" />
           
        DockPanel>

3-      You can write your suitable code into button to allow user to open dialogue and it’s easy for you to implement.
4-      In Main Window > declare the xmlns attribute
                        xmlns:my="clr-namespace:WpfApplication3"

Here ‘s the final code
<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:my="clr-namespace:WpfApplication3"
        Title="MainWindow" Height="350" Width="525" xmlns:shared="http://schemas.actiprosoftware.com/winfx/xaml/shared" xmlns:navigation="http://schemas.actiprosoftware.com/winfx/xaml/navigation" xmlns:docking="http://schemas.actiprosoftware.com/winfx/xaml/docking" xmlns:editors="http://schemas.actiprosoftware.com/winfx/xaml/editors" xmlns:ribbon="http://schemas.actiprosoftware.com/winfx/xaml/ribbon">
    <Grid>
        <StackPanel Margin="20">
            <my:UserControl1 Height="67" Width="278" />
        StackPanel>
    Grid>
Window>

0 التعليقات: