WPF controls and dynamically add style dictionary of reference (Style introduction)

Original: WPF controls and dynamically add style dictionary of reference (Style introduction)

  The results we want to achieve that bind multiple Checkbox then we can get if it is selected, is actually very simple, as long as we find that a few key objects on it.

  Below are Ui, which defines a WrapPanel to store the CheckBox, there are two buttons for test-related functions.

<Window x:Class="WpfApplication1.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:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid  Name="div" >
        <StackPanel Margin="0,50,0,0" Orientation="Horizontal"  HorizontalAlignment="Center">
            <StackPanel>
                <Button Content="动态添加多个checkbox控件" Height="20" Padding="15,1,15,2" x:Name="btnAdd" Click="btnAdd_Click"></Button>
            </StackPanel>

        </StackPanel>

        <ScrollViewer ScrollViewer.VerticalScrollBarVisibility="Auto" Height="150">
            <Border   BorderBrush="#797979" BorderThickness="1" Margin="5,0,5,5">
                <WrapPanel x:Name="addCheckbox"/>
            </Border>
        </ScrollViewer>
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="37,261,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
        <Button x:Name="button1" Content="Button" HorizontalAlignment="Left" Margin="379,50,0,0" VerticalAlignment="Top" Width="75" Click="button1_Click"/>
    </Grid>
</Window>

  Checkbox dynamically add, we define a CheckBox array, and thereafter ThickNess instantiated object, which is used to describe the thickness of the surrounding rectangle and then we cycle length of the array to be added (where name is addCheckbox of control) , so far, checkbox has been added dynamically.

  How then delete it? We still need to get the sons named addCheckbox of control (Children) to remove. Consider the following code snippet.

private void button1_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < addCheckbox.Children.Count;)
            {
                this.addCheckbox.Children.Remove(addCheckbox.Children[i]);
            }
        }

Cycle where the value is very simple, because we in the above binding, has given its Content or both DataContext assignment, so we just get on ok.

private void button_Click(object sender, RoutedEventArgs e)
        {
            foreach (UIElement item in addCheckbox.Children)
            {
                if (item is CheckBox)
                {
                    CheckBox checkbox = (item as CheckBox);
                    if (checkbox.IsChecked == true)
                    {
                        MessageBox.Show(checkbox.Content.ToString());
                    }
                }
            }
        }

 Finally, the effect is generated out of this, is not very ugly, then I'll teach you how to make simple landscaping.

 We add checkbox when introduced in two ways, one is  checkbox.Style = Resources [ " NoticeBox " ] AS Style;  other words are  Style = style (Style) the this .FindResource ( " NoticeButton " );  those two What's the difference?

The first is the resource file reference must be to the current page, and the second is to find not included (external resource files) app.xaml introduced in App.xaml. Let's write a CheckBox style in the app, xaml in.

<Application x:Class="WpfApplication1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApplication1"
             StartupUri="MainWindow.xaml">

    <Application.Resources>
        <Style x:Key="CheckBoxSwitchStyle" TargetType="CheckBox">
            <Setter Property="IsChecked" Value="False"/>
            <Setter Property="Cursor" Value="Hand"/>
            <Setter Property="FontFamily" Value="/MESToolIntegration;component/Fonts/#iconfont"/>
            <Setter Property="Background" Value="#FFFFFF"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="CheckBox">
                        <Border Width="54" Name="CheckTrueBG" Height="22" BorderThickness="1" Background="#FFFFFF"  CornerRadius="10" BorderBrush="#ACACAC" >
                            <Grid>
                                <Border BorderThickness="1" Background="#ACACAC" x:Name="border" Width="20" Height="20" CornerRadius="9" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="0"  >
                                    <Border.RenderTransform>
                                        <TranslateTransform  X="1"/>
                                    </Border.RenderTransform>
                                </Border>
                                <TextBlock x:Name="txt" Text="{TemplateBinding Content}" FontFamily="iconfont"  FontSize="{TemplateBinding FontSize}" Margin="6.996,2.798,0,2.798" VerticalAlignment="Stretch" Foreground="#ACACAC" HorizontalAlignment="Left" >
                                    <TextBlock.RenderTransform>
                                        <TranslateTransform   X="17"></TranslateTransform>
                                    </TextBlock.RenderTransform>
                                </TextBlock>
                            </Grid>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsChecked" Value="true">
                                <Setter Property="Background" TargetName="CheckTrueBG"  Value="#5FB878"/>
                                <Setter Property="Foreground" TargetName="txt"  Value="#FFFFFF"/>
                                <Setter Property="Background" TargetName="border"  Value="#FFFFFF"/>
                                <Setter Property="Text" TargetName="txt" Value="{Binding Tag,RelativeSource={RelativeSource TemplatedParent}}"/>
                                <Trigger.EnterActions>
                                    <BeginStoryboard>
                                        <Storyboard>
                                            <DoubleAnimation Storyboard.TargetName="border" Storyboard.TargetProperty="(UIElement.RenderTransform).(TranslateTransform.X)" To="32" Duration="00:00:0.2"/>
                                            <DoubleAnimation Storyboard.TargetName="txt" Storyboard.TargetProperty="(UIElement.RenderTransform).(TranslateTransform.X)" To="0" Duration="00:00:0.2"/>
                                        </Storyboard>
                                    </BeginStoryboard>
                                </Trigger.EnterActions>
                                <Trigger.ExitActions>
                                    <BeginStoryboard>
                                        <Storyboard>
                                            <DoubleAnimation Storyboard.TargetName="border" Storyboard.TargetProperty="(UIElement.RenderTransform).(TranslateTransform.X)" To="0" Duration="00:00:0.2"/>
                                            <DoubleAnimation Storyboard.TargetName="txt" Storyboard.TargetProperty="(UIElement.RenderTransform).(TranslateTransform.X)" To="17" Duration="00:00:0.2"/>
                                        </Storyboard>
                                    </BeginStoryboard>
                                </Trigger.ExitActions>
                            </Trigger>
                            <Trigger Property="IsChecked" Value="False">
                                <Setter Property="Text" TargetName="txt" Value="{Binding Content,RelativeSource={RelativeSource TemplatedParent}}"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Application.Resources>
</Application>

In this way we generate a CheckBox configured in the code below.

private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            int num = 6;
            CheckBox[] check = new CheckBox[num];
            Thickness th = new Thickness();
            th.Bottom = 10;
            th.Left = 10;
            th.Right = 10;
            th.Top = 10;
            for (int i = 0; i < check.Length; i++)
            {
                check[i] = new CheckBox();
                //设置checkbox属性
                check[i].Margin = th;
                check[i].Content = i + 1;
                check[i].Name = "heheda";
                check[i].DataContext = "asdas";
                check[i].Style = (Style)this.FindResource("CheckBoxSwitchStyle");
          this.addCheckbox.Children.Add(check[i]);
            }
        }

 Start page we can see that the introduction of a success.

 Not difficult to find, look at the code, how do we want to write another style, this time how should I do? Is it still possible to app.xaml to write? This is very sick, so we use the introduction of this and a bit like css! Create a new resource dictionary.

Write to write in the following style.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:WpfApplication1">
    <Style x:Key="BtnInfoStyle" TargetType="Button">
        <Setter Property="Width" Value="70"/>
        <Setter Property="Height" Value="25"/>
        <Setter Property="Foreground" Value="White"/>
        <Setter Property="BorderThickness" Value="0"/>
        <Setter Property="Background" Value="#43a9c7"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border x:Name="border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" SnapsToDevicePixels="True">
                        <TextBlock Text="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter TargetName="border" Property="Background" Value="#2f96b4"/>
                        </Trigger>
                        <Trigger Property="IsPressed" Value="True">
                            <Setter TargetName="border" Property="Background" Value="#2a89a4"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

然后在app.xaml中进行引用,这里需要注意是,有可能我们的style和外部字典都放进去了,它们的关系是style其实也是一个字典,然后就变成了这样。

<Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary1.xaml"/>
            </ResourceDictionary.MergedDictionaries>
            <Style x:Key="CheckBoxSwitchStyle" TargetType="CheckBox">
                <Setter Property="IsChecked" Value="False"/>
                <Setter Property="Cursor" Value="Hand"/>
                <Setter Property="FontFamily" Value="/MESToolIntegration;component/Fonts/#iconfont"/>
                <Setter Property="Background" Value="#FFFFFF"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="CheckBox">
                            <Border Width="54" Name="CheckTrueBG" Height="22" BorderThickness="1" Background="#FFFFFF"  CornerRadius="10" BorderBrush="#ACACAC" >
                                <Grid>
                                    <Border BorderThickness="1" Background="#ACACAC" x:Name="border" Width="20" Height="20" CornerRadius="9" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="0"  >
                                        <Border.RenderTransform>
                                            <TranslateTransform  X="1"/>
                                        </Border.RenderTransform>
                                    </Border>
                                    <TextBlock x:Name="txt" Text="{TemplateBinding Content}" FontFamily="iconfont"  FontSize="{TemplateBinding FontSize}" Margin="6.996,2.798,0,2.798" VerticalAlignment="Stretch" Foreground="#ACACAC" HorizontalAlignment="Left" >
                                        <TextBlock.RenderTransform>
                                            <TranslateTransform   X="17"></TranslateTransform>
                                        </TextBlock.RenderTransform>
                                    </TextBlock>
                                </Grid>
                            </Border>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsChecked" Value="true">
                                    <Setter Property="Background" TargetName="CheckTrueBG"  Value="#5FB878"/>
                                    <Setter Property="Foreground" TargetName="txt"  Value="#FFFFFF"/>
                                    <Setter Property="Background" TargetName="border"  Value="#FFFFFF"/>
                                    <Setter Property="Text" TargetName="txt" Value="{Binding Tag,RelativeSource={RelativeSource TemplatedParent}}"/>
                                    <Trigger.EnterActions>
                                        <BeginStoryboard>
                                            <Storyboard>
                                                <DoubleAnimation Storyboard.TargetName="border" Storyboard.TargetProperty="(UIElement.RenderTransform).(TranslateTransform.X)" To="32" Duration="00:00:0.2"/>
                                                <DoubleAnimation Storyboard.TargetName="txt" Storyboard.TargetProperty="(UIElement.RenderTransform).(TranslateTransform.X)" To="0" Duration="00:00:0.2"/>
                                            </Storyboard>
                                        </BeginStoryboard>
                                    </Trigger.EnterActions>
                                    <Trigger.ExitActions>
                                        <BeginStoryboard>
                                            <Storyboard>
                                                <DoubleAnimation Storyboard.TargetName="border" Storyboard.TargetProperty="(UIElement.RenderTransform).(TranslateTransform.X)" To="0" Duration="00:00:0.2"/>
                                                <DoubleAnimation Storyboard.TargetName="txt" Storyboard.TargetProperty="(UIElement.RenderTransform).(TranslateTransform.X)" To="17" Duration="00:00:0.2"/>
                                            </Storyboard>
                                        </BeginStoryboard>
                                    </Trigger.ExitActions>
                                </Trigger>
                                <Trigger Property="IsChecked" Value="False">
                                    <Setter Property="Text" TargetName="txt" Value="{Binding Content,RelativeSource={RelativeSource TemplatedParent}}"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ResourceDictionary>
    </Application.Resources>

我把缩进的截图发上来,更直观。

 在其中还有内嵌的样式,可以这么写,如果是page的话你就 <Page.Resources> ,如果是windows的话那就Wndows,当然如果需要页面引入字典的话你可以这么做。

<Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Style/test.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>

那么今天就这样~

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/11272606.html