WPF代码注意事项,开发常见问题,知识总结

时间:2021-12-15 10:46:44

代码注意事项:

1、代码实现的样式赋值

XXX.Style = TryFindResource("StyleName") as Style;

2.WPF中FindName方法的使用

 (1)简单的使用 前台代码:

<Button x:Name="btnName" Click="btnName_Click">Test Method FindName</Button>

  后台代码:

private void btnName_Click(object sender, RoutedEventArgs e)

{

  Button b = FindName("btnName") as Button;

  MessageBox.Show(b.Name);

}

(2)在模板中使用FindName方法

<Grid>
     <Grid x:Name="childGrid">
         <Button x:Name="rootBtn">
             <Button.Template>
                 <ControlTemplate>
                     <Button x:Name="btnName" Click="btnName_Click">Test Method FindName</Button>
                 </ControlTemplate>
             </Button.Template>
         </Button>
       
     </Grid>
 </Grid>

 后台代码:

private void btnName_Click(object sender, RoutedEventArgs e)
    {
        Button b = rootBtn.Template.FindName("btnName",rootBtn) as Button;
        MessageBox.Show(b.Name);
    }

3.使用多个绑定参数

<Button Height="23" Command="{Binding AddCommand}"   Content="计算"
                HorizontalAlignment="Left" Margin="20,0,0,49" Name="button1" VerticalAlignment="Bottom" Width="75">
           <Button.CommandParameter>
               <MultiBinding Converter="{StaticResource ParameterConverter}">
                   <Binding Path="Text" ElementName="textBox1"/>
                   <Binding Path="Text" ElementName="textBox2"/>
               </MultiBinding>
           </Button.CommandParameter>

4、将代码写在XAML中

<Grid>
    <x:Code>  <![CDATA[
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        button1.Background = Brushes.Blue;
        button1.Content = "The code is in XAML";
        MessageBox.Show("hi");
    }
    ]]></x:Code>
    <Button Height="23" Margin="46,56,32,0" Name="button1" VerticalAlignment="Top" Click="button1_Click">Click me!</Button>
</Grid>

5、各属性对应的C#代码

5.1<Window><Grid><Button ...></Grid></window>

  等效代码如下:

Grid g = new Grid();
Button b = new Button();
b.Width = 100;
b.Height = 100;
b.Content = "Test Button";
b.Foreground = Brushes.LightBlue;
g.Children.Add(b);
myWindow.AddChild(g);

6、ItemContainerGenerator.ContainerFromIndex方法的使用

TreeViewItem item = (TreeViewItem)myTreeView.ItemContainerGenerator.ContainerFromIndex(1);

7、WPF获取子控件和父控件方法 

public class Globals
    {
        /// <summary>
        /// 获取父控件方法。该方法将根据当前控件,遍历查找其父控件是否存在。参数1是表示当前子控件名,参数2是要查询父控件名;
        /// </summary>
        public T GetParentObject<T>(DependencyObject obj, string name) where T : FrameworkElement
        {
            DependencyObject parent = VisualTreeHelper.GetParent(obj);
            while (parent != null)
            {
                if (parent is T && (((T)parent).Name == name | string.IsNullOrEmpty(name)))
                {
                    return (T)parent;
                }
                parent = VisualTreeHelper.GetParent(parent);
            }
            return null;
        }
        /// <summary>
        /// 该方法将根据当前控件,遍历查找其子控件是否存在。参数1是表示当前父控件名,参数2是要查询子控件名;
        /// </summary>
        public T GetChildObject<T>(DependencyObject obj, string name) where T : FrameworkElement
        {
            DependencyObject child = null;
            T grandChild = null;
            for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
            {
                child = VisualTreeHelper.GetChild(obj, i);
                if (child is T && (((T)child).Name == name | string.IsNullOrEmpty(name)))
                {
                    return (T)child;
                }
                else
                {
                    grandChild = GetChildObject<T>(child, name);
                    if (grandChild != null)
                        return grandChild;
                }
            }
            return null;
        }
        /// <summary>
        /// 该方法将把所有子控件作为List集合返回到客户端。
        /// 其中第一个参数是父控件参数,而第二个参数是特定子控件名称,
        /// 如果需要遍历全部子控件,第二个参数留空即可。
        /// </summary>
        public List<T> GetChildObjects<T>(DependencyObject obj, string name) where T : FrameworkElement
        {
            DependencyObject child = null;
            List<T> childList = new List<T>();
            for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
            {
                child = VisualTreeHelper.GetChild(obj, i);
                if (child is T && (((T)child).Name == name || string.IsNullOrEmpty(name)))
                {
                    childList.Add((T)child);
                }
                childList.AddRange(GetChildObjects<T>(child, ""));
            }
            return childList;
        }
    }

  

XAML:

Globals VTHelper = new Globals();
StackPanel sp = VTHelper.GetChildObject<StackPanel>(this.LayoutRoot, "spDemoPanel");
Grid layoutGrid = VTHelper.GetParentObject<Grid>(this.spDemoPanel, "LayoutRoot");
List<TextBlock> textblock = VTHelper.GetChildObjects<TextBlock>(this.LayoutRoot, "");

  

8.GridSplitter控件的使用:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="90*" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="180*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="190*" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="70*" />
    </Grid.RowDefinitions>
    <Button Content="ButtonA" Margin="3" Grid.Row="0" Grid.Column="0" Grid.RowSpan="3" />
    <Button Content="ButtonB" Margin="3" Grid.Row="0" Grid.Column="2" />
    <Button Content="ButtonC" Margin="3" Grid.Row="2" Grid.Column="2" />
    <GridSplitter Width="3" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"   Grid.Row="0" Grid.Column="1" Grid.RowSpan="3"></GridSplitter>
    <GridSplitter Height="3" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"  Grid.Row="1" Grid.Column="2"></GridSplitter>
</Grid>

效果图:

WPF代码注意事项,开发常见问题,知识总结

9.UniformGrid控件中每行没列都相等

<UniformGrid>
    <Button Content="ButtonA" />
    <Button Content="ButtonB" />
    <Button Content="ButtonC" />
    <Button Content="ButtonD" />
    <Button Content="ButtonE" />
    <Button Content="ButtonF" />
    <Button Content="ButtonG" />
    <Button Content="ButtonH" />
</UniformGrid>

如图:

WPF代码注意事项,开发常见问题,知识总结

http://www.cnblogs.com/linlf03/archive/2011/09/07/2159169.html