【问题标题】:Create a Custom Control with the combination of multiple controls in WPF C#在 WPF C# 中使用多个控件的组合创建自定义控件
【发布时间】:2016-12-14 23:43:46
【问题描述】:

我希望创建一个自定义控件,它应该是文本框、按钮、列表框等预定义控件的组合,

请参考以下控件(只是一个示例)

<Grid.RowDefinitions>
    <RowDefinition Height="30" />
    <RowDefinition Height="50" />
</Grid.RowDefinitions>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="300" />
        <ColumnDefinition Width="100" />
    </Grid.ColumnDefinitions>
    <TextBox Grid.Column="0" />
    <Button Grid.Column="1" Content="Add" Margin="20,0" />
</Grid>
<ListBox ItemsSource="{Binding textBox}" Grid.Row="1" Margin="0,25">
    <ListBoxItem />
</ListBox>
</Grid>

我需要一个自定义控件中的控件组合。当我点击按钮时,我需要在 ListItem 中添加文本框值,最后我需要来自该控件的 List。

预期的自定义控件(只是一个示例)

<cust:MultiControl ItemsSource="{Binding stringCollection}" />

说明: 我需要从用户那里获取字符串列表。我添加了一个文本框来获取用户的输入。我添加了一个按钮来在List&lt;string&gt; 中添加文本。为了显示列表,我添加了一个 ListBox。

我需要一个Single控件,它应该继承这三个控件。我需要一个ItemsSource 用于双向绑定。如果List&lt;string&gt; 被更新,它应该更新ItemSource。

我在超过 15 个地方使用这种结构。所以,我希望将其作为自定义控件。请帮助我如何将其作为单个控件来实现?

我不需要用户控件,我需要自定义控件,请帮助我...

即使 ItemsSource 有价值,项目源 ViewModel 集合也不会更新。

【问题讨论】:

  • CustomControl 只是一个派生自 Control 的类。 UserControl 也是从 Control(间接)派生​​的类,因此 UserControl 是 CustomControl。 UserControl 的优点在于您可以使用 XAML 文件 + 代码轻松定义它们,而 CustomControl 只是代码。所以你真的想要一个用户控件。您只需为其添加自定义代码,例如 DependencyProperties(用于您公开的 ItemSource)和自定义逻辑。
  • 您基本上需要一个工作自定义控件的示例吗?如何从头开始构建?
  • 请告诉我们,您为什么不简单地制作一个CustomControl?你怎么了?如果您知道如何编写 UserControl,那么编写 CustomControl 应该没有问题...我真的不明白 what 你在问什么
  • @lok​​usking 我需要一个具有我在问题中提到的结构的控件。因为我需要一个ItemSource 属性来绑定List&lt;string&gt;。控件应具有我在问题中提到的所有功能。您可能对我的用户控制方式的要求有解决方案,然后给出您的答案。

标签: c# .net wpf xaml custom-controls


【解决方案1】:

我为您制作了所需 CustomControl 的最小示例。

控制

public class MyCustomControl : ItemsControl {

        static MyCustomControl() {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl)));
        }

        private Button _addButton;
        private TextBox _textBox;
        private ListView _itemsView;

        public override void OnApplyTemplate() {
            this._addButton = this.GetTemplateChild("PART_AddButton") as Button;
            this._textBox = this.GetTemplateChild("PART_TextBox") as TextBox;
            this._itemsView = this.GetTemplateChild("PART_ListBox") as ListView;

            this._addButton.Click += (sender, args) => {
                (this.ItemsSource as IList<string>).Add(this._textBox.Text);
            };
            this._itemsView.ItemsSource = this.ItemsSource;
            base.OnApplyTemplate();
        }

        public ICommand DeleteCommand => new RelayCommand(x => { (this.ItemsSource as IList<string>).Remove((string)x); });
    }

模板

 <Style TargetType="{x:Type local:MyCustomControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MyCustomControl}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="Auto" />
                        </Grid.RowDefinitions>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="300" />
                                <ColumnDefinition Width="100" />
                            </Grid.ColumnDefinitions>
                            <TextBox x:Name="PART_TextBox" Grid.Column="0" />
                            <Button x:Name="PART_AddButton" Grid.Column="1" Content="Add" Margin="20,0" />
                        </Grid>
                        <ListView ItemsSource="{TemplateBinding ItemsSource}" Grid.Row="1" Margin="0,25" x:Name="PART_ListBox" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch">
                                        <TextBlock Text="{Binding}"/>
                                        <Button Content="X" Foreground="Red" 
                                                Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MyCustomControl}}, Path=DeleteCommand}" 
                                                CommandParameter="{Binding}" Margin="10,0,0,0"></Button>
                                    </StackPanel>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                        </ListView>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

中继命令

public class RelayCommand : ICommand
    {
        #region Fields

        private readonly Action<object> _execute;
        private readonly Predicate<object> _canExecute;

        #endregion // Fields

        #region Constructors

        public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
        {
            if (execute == null)
                throw new ArgumentNullException(nameof(execute));

            this._execute = execute;
            this._canExecute = canExecute;
        }

        #endregion // Constructors

        #region ICommand Members

        [DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            return this._canExecute == null || this._canExecute(parameter);
        }

        public event EventHandler CanExecuteChanged {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            this._execute(parameter);
        }

        #endregion // ICommand Members
    }

用法

 <local:MyCustomControl ItemsSource="{Binding Collection}"/>

注意 不要使用 List 作为您的 ItemsSource。而是使用ObservableCollection,因为它会自动通知视图,您不必处理该更新内容

干杯

【讨论】:

  • 非常感谢...这太棒了,这是我的实际期望。感谢您的指导。
  • 谢谢。我需要一个额外的选项来从列表中删除项目。
  • @IRPunch 使用 deleteButton 更新了控件
  • @lok​​usking - 谢谢。但我需要在&lt;ListView.ItemTemplate&gt; 中的每个特定项目中都有一个删除按钮,我需要一个删除按钮来删除该项目。
  • @lok​​usking - 我尝试了一个具有相同逻辑的自动完成文本框。我又添加了一个依赖属性IEnumerable&lt;dynamiic&gt;SuggestionItemSource。我在列表框中绑定了属性。如果我绑定一个ObservableCollection&lt;string&gt;,那么它可以完美运行,如果我使用ObservableCollection &lt;int&gt;,那么它就不行了。
【解决方案2】:

假设这是您的自定义控件:

<UserControl x:Class="CustomControl.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:CustomControl"
         mc:Ignorable="d" >
<StackPanel Width="200" Margin="15">
    <TextBox  Name="txtbox"/>
    <Button  Content="Add"
            Margin="20,0"  Click="Button_Click"/>

    <ListBox ItemsSource="{Binding}"
             Margin="0,25">
    </ListBox>

</StackPanel>

这是你的父窗口调用你的自定义控件:

<Window x:Class="ParentControl.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:ParentControl"
    mc:Ignorable="d"
    xmlns:customcontrol="clr-namespace:CustomControl;assembly=CustomControl"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <customcontrol:UserControl1 Name="customcontrol"></customcontrol:UserControl1>
</Grid>

你有一个字符串集合,你想用文本框中的文本来更新它,你可以这样做: 在父窗口中将自定义控件的DataContext设置为字符串集合,如下所示:

        public MainWindow()
    {
        InitializeComponent();

        ObservableCollection<string> stringcollection = new ObservableCollection<string>();
        stringcollection.Add("String 1");
        stringcollection.Add("String 2");
        stringcollection.Add("String 2");
        stringcollection.Add("String 3");
        customcontrol.DataContext = stringcollection;

    }

并在您的自定义控件返回逻辑中将处理程序添加到按钮单击事件并执行以下操作:

 private void Button_Click(object sender, RoutedEventArgs e)
    {
        var button = sender as Button;
        var list = button.DataContext as ObservableCollection<string>;
        list.Add(this.txtbox.Text.ToString());
    }

确保字符串集合是 Observable Collection 类型,否则每次单击添加按钮时列表框都不会更新。

希望对您有所帮助。

【讨论】:

  • 我期待自定义控件中的解决方案不是由 UserControl 提供的。感谢您的友好回复...
  • 没有。它不是自定义控件。只需参考我在问题块中添加的屏幕截图。
  • 我需要这个作为一个独立的控件。如果我实现用户控制方式,它依赖于项目级别(即父窗口级别)。
猜你喜欢
  • 1970-01-01
  • 2012-05-25
  • 1970-01-01
  • 1970-01-01
  • 2011-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-19
相关资源
最近更新 更多