如何在我的UserControl中存储控件列表,并能够从xaml进行设置 [英] How to store list of Controls inside my UserControl, and be able to set them from the xaml

查看:62
本文介绍了如何在我的UserControl中存储控件列表,并能够从xaml进行设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,

我想在xaml的用户控件中设置一个FrameworkElements列表.假设我的课程定义是:

MyControl类:UserControl

{

公共列表< FrameworkElement> ControlList {get;放; }

}

 

然后,我希望能够在xaml中执行以下操作:

< MyControl>

   < Button/>

   <画布/>

   <图片/>

</MyControl>

按钮,画布和图像都存储在MyControl的"ControlList"中

 

最干净的方法是什么?


Slo

解决方案

XML的示例代码

 

< Window x:Class =" WpfApplication.Grid"名称=此"
       xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
       xmlns:local ="clr-命名空间:WpfApplication"
      标题=网格". mc:Ignorable ="d" xmlns:d ="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006" d:DesignHeight ="301". d:DesignWidth ="438". SizeToContent =" WidthAndHeight">
    < Window.Resources>

       < local:BoolToVisibilityConverter x:Key ="boolToVis" />

       < Style TargetType =" {x:Type TextBlock}"
          x:Key ="GridBlockStyle">
           < Setter Property ="VerticalAlignment";值=中心". />
           < Setter Property ="Visibility"
           值=" {Binding Path = IsSelected,
            RelativeSource = {RelativeSource FindAncestor,
               b AncestorType = {x:Type ListViewItem}},
            Converter = {StaticResource boolToVis},
              nbsp; b ConverterParameter = False}" />
       </Style>
      
       < Style TargetType =" {x:Type FrameworkElement}
          x:Key =" GridEditStyle">
           < Setter Property ="VerticalAlignment";值=中心". />
           < Setter Property ="Visibility"
           值=" {Binding Path = IsSelected,
            RelativeSource = {RelativeSource FindAncestor,
               b AncestorType = {x:Type ListViewItem}},
            Converter = {StaticResource boolToVis},
              nbsp; b ConverterParameter = True}" />
       </Style>
    </Window.Resources>
    < Grid Height =" {Binding RelativeSource =
     {RelativeSource AncestorType = {x:Type窗口}},路径=高度,
     Converter = {local:DebugBinding}}>
       < ListView Margin ="0,0,0,0&"名称="ListView1"; ItemsSource =
       < {Binding ElementName = This,Path = MyProperty}" >
           < ListView.View>
                             < GridView>
                    < GridViewColumn Header ="display" DisplayMemberBinding =""{Binding display}">
                    </GridViewColumn>
                    < GridViewColumn Header =已许可" DisplayMemberBinding =""{已绑定绑定}">
                    </GridViewColumn>
                    < GridViewColumn Header ="client_address" >
               b < GridViewColumn.CellTemplate>
              nbsp; bsp    < DataTemplate>
              nbsp; bsp       < Grid Horizo​​ntalAlignment =拉伸">
              nbsp; bsp           < TextBlock Text =" {Binding Path = client_address}"
              nbsp; bsp             样式=""{StaticResource GridBlockStyle}"/>
              nbsp; bsp           < ComboBox SelectedValue =< {Binding Id}"
              nbsp; bsp              ItemsSource =""{绑定 ElementName = This,Path = obj}"
              nbsp; bsp              DisplayMemberPath ="client_address"; SelectedValuePath ="Id";
              nbsp; bsp             样式=""{StaticResource GridEditStyle}>
              nbsp; bsp           </ComboBox>
              nbsp; bsp       </Grid>
              nbsp; bsp    </DataTemplate>
               b </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    < GridViewColumn Header ="local_library"; DisplayMemberBinding =""{Binding Path = local_library}">
                    </GridViewColumn>
                    < GridViewColumn Header =更新">
               b < GridViewColumn.CellTemplate>
              nbsp; bsp    < DataTemplate>
              nbsp; bsp       <按钮名称=更新";内容=更新";点击="Update_Click" ></Button>
              nbsp; bsp    </DataTemplate>
               b </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                             </GridView>
           </ListView.View>
       </ListView>
    </Grid>
</Window>

 

 

 

 

 

 

 

代码隐藏示例

 

 

 

 

使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Text;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Data;
使用System.Windows.Documents;
使用System.Windows.Input;
使用System.Windows.Media;
使用System.Windows.Media.Imaging;
使用System.Windows.Shapes;
使用System.Collections;
使用System.Data;

命名空间WpfApplication
{
   公共局部类Grid:Window
    {
      公共Grid()
       {
           InitializeComponent();
           _obj = Connection.BindCombo();
           ListView1.ItemsSource = MyProperty;
       }

      私有列表< Display> _obj = null;
      公共列表< Display> obj {get {return _obj; }}
      公共列表< Display> MyProperty {get {return Connection.BindDisplay(); }}

      私有void Update_Click(对象发送者,RoutedEventArgs e)
       {
           ListViewItem lvi = GetDependencyObjectFromVisualTree(e.OriginalSource作为DependencyObject,typeof(ListViewItem))作为ListViewItem;

       }

      私有DependencyObject GetDependencyObjectFromVisualTree(DependencyObject startObject,Type type)
       {

           //迭代可视树以获取此控件的父级(ItemsControl)

           DependencyObject parent = startObject;

           while(parent!= null)
           {

                            如果(type.IsInstanceOfType(parent))

                   休息;

                            其他

                    parent = VisualTreeHelper.GetParent(parent);

           }

          返回父母;

       }

    }


   公共类BoolToVisibilityConverter:IValueConverter
    {
      公共对象Convert(对象值,类型为targetType,
        对象参数,System.Globalization.CultureInfo文化)
       {
           bool param = bool.Parse(参数为字符串);
           bool val =(bool)value;

           return val == param?
            Visibility.Visible:Visibility.Hidden;
       }

      公共对象ConvertBack(对象值,类型为targetType,
        对象参数,System.Globalization.CultureInfo文化)
       {
          抛出新的NotImplementedException();
       }
    }
}


Hey,

I want to set a list of FrameworkElements in my user control from xaml. Assume my class definition is:

class MyControl : UserControl

{

public List<FrameworkElement> ControlList { get; set; }

}

 

Then I want to be able to do something like this in xaml:

<MyControl >

   <Button/>

   <Canvas/>

   <Image/>

</MyControl >

Where the button, canvas, and image are all stored in 'ControlList' on MyControl

 

Whats the cleanest way to do this?


Slo

解决方案

Sample code for XML

 

<Window x:Class="WpfApplication.Grid" Name="This"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication"
        Title="Grid" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" d:DesignHeight="301" d:DesignWidth="438" SizeToContent="WidthAndHeight">
    <Window.Resources>

        <local:BoolToVisibilityConverter x:Key="boolToVis" />

        <Style TargetType="{x:Type TextBlock}"
           x:Key="GridBlockStyle">
            <Setter Property="VerticalAlignment" Value="Center" />
            <Setter Property="Visibility"
              Value="{Binding Path=IsSelected,
              RelativeSource={RelativeSource FindAncestor,
                        AncestorType={x:Type ListViewItem}},
              Converter={StaticResource boolToVis},
                         ConverterParameter=False}" />
        </Style>
       
        <Style TargetType="{x:Type FrameworkElement}"
           x:Key="GridEditStyle">
            <Setter Property="VerticalAlignment" Value="Center" />
            <Setter Property="Visibility"
              Value="{Binding Path=IsSelected,
              RelativeSource={RelativeSource FindAncestor,
                        AncestorType={x:Type ListViewItem}},
              Converter={StaticResource boolToVis},
                         ConverterParameter=True}" />
        </Style>
    </Window.Resources>
    <Grid Height="{Binding RelativeSource =
      {RelativeSource AncestorType={ x:Type Window}}, Path =Height,
      Converter={local:DebugBinding }}">
        <ListView Margin="0,0,0,0"  Name="ListView1" ItemsSource=
        "{Binding ElementName=This, Path=MyProperty}" >
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="display" DisplayMemberBinding="{Binding display}">
                    </GridViewColumn>
                    <GridViewColumn Header="licensed" DisplayMemberBinding="{Binding licensed}">
                    </GridViewColumn>
                    <GridViewColumn Header="client_address" >
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Grid HorizontalAlignment="Stretch">
                                    <TextBlock Text="{Binding Path=client_address}"
                                        Style="{StaticResource GridBlockStyle}"/>
                                    <ComboBox SelectedValue="{Binding Id}"
                                        ItemsSource="{Binding ElementName=This,Path = obj}"
                                        DisplayMemberPath="client_address" SelectedValuePath="Id"
                                        Style="{StaticResource GridEditStyle}">
                                    </ComboBox>
                                </Grid>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Header="local_library" DisplayMemberBinding="{Binding Path=local_library}">
                    </GridViewColumn>
                    <GridViewColumn Header="Update">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Button Name="Update" Content="Update" Click="Update_Click" ></Button>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

 

 

 

 

 

 

 

Sample code in Code Behind

 

 

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections;
using System.Data;

namespace WpfApplication
{
    public partial class Grid : Window
    {
        public Grid()
        {
            InitializeComponent();
            _obj = Connection.BindCombo();
            ListView1.ItemsSource = MyProperty;
        }

        private List<Display> _obj = null;
        public List<Display> obj { get { return _obj; } }
        public List<Display> MyProperty { get { return Connection.BindDisplay(); } }

        private void Update_Click(object sender, RoutedEventArgs e)
        {
            ListViewItem lvi = GetDependencyObjectFromVisualTree(e.OriginalSource as DependencyObject, typeof(ListViewItem)) as ListViewItem;

        }

        private DependencyObject GetDependencyObjectFromVisualTree(DependencyObject startObject, Type type)
        {

            //Iterate the visual tree to get the parent(ItemsControl) of this control

            DependencyObject parent = startObject;

            while (parent != null)
            {

                if (type.IsInstanceOfType(parent))

                    break;

                else

                    parent = VisualTreeHelper.GetParent(parent);

            }

            return parent;

        }

    }


    public class BoolToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType,
          object parameter, System.Globalization.CultureInfo culture)
        {
            bool param = bool.Parse(parameter as string);
            bool val = (bool)value;

            return val == param ?
              Visibility.Visible : Visibility.Hidden;
        }

        public object ConvertBack(object value, Type targetType,
          object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}


这篇关于如何在我的UserControl中存储控件列表,并能够从xaml进行设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆