【发布时间】:2017-09-29 10:21:36
【问题描述】:
我在窗口上有一组按钮。当我单击该按钮时,我想动态添加不同的控件。 考虑我有两个按钮 1> 添加文本框 2>添加按钮
当我点击 AddTextButton 时,应该将 TextBox 添加到窗口 当我点击 AddButton 时,应该添加 Button
【问题讨论】:
-
“通过 xaml” ?动态通常意味着以编程方式(参见this answer)。
我在窗口上有一组按钮。当我单击该按钮时,我想动态添加不同的控件。 考虑我有两个按钮 1> 添加文本框 2>添加按钮
当我点击 AddTextButton 时,应该将 TextBox 添加到窗口 当我点击 AddButton 时,应该添加 Button
【问题讨论】:
你可以添加如下代码sn-p,
private void AddButtonClick(object sender, RoutedEventArgs e)
{
var rowCount = this.grid.RowDefinitions.Count;
this.grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
var button = new Button() { Content = "Button1", Height = 20, Width = 50 };
Grid.SetRow(button, rowCount + 1);
this.grid.Children.Add(button);
}
【讨论】:
如果您想通过绑定动态添加按钮,以下方法可能会对您有所帮助。
首先,您将 ItemsControl 部分添加到定义 ItemTemplate 的 xaml。
<ItemsControl ItemsSource="{Binding DynamicControlObjects}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Text}"
ToolTip="{Binding Tooltip}"
IsEnabled="{Binding IsEnabled}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
DynamicControlObjects 只是一个简单的IList<T>,其中T 是一个包含您要绑定的属性的类。
例如我在这种情况下使用的是我的班级DynamicControlHelper:
// ...
using Microsoft.Practices.Prism.ViewModel;
// ...
public class DynamicControlHelper : NotificationObject
{
#region Backing Fields
private string _text;
private bool _isEnabled;
private string _tooltip;
#endregion Backing Fields
#region Properties
public string Text
{
get
{
return this._text;
}
set
{
if (!string.Equals(this._text, value))
{
this._text = value;
this.RaisePropertyChanged(nameof(this.Text));
}
}
}
public bool IsEnabled
{
get
{
return this._isEnabled;
}
set
{
if (this._isEnabled != value)
{
this._isEnabled = value;
this.RaisePropertyChanged(nameof(IsEnabled));
}
}
}
// ...
public string Tooltip
{
get
{
return this._tooltip;
}
set
{
if (!string.Equals(this._tooltip, value))
{
this._tooltip = value;
this.RaisePropertyChanged(nameof(this.Tooltip));
}
}
}
#endregion Properties
}
当我第一次需要这种方法时。来自H.B. 的The answer 引导我找到我的解决方案。
【讨论】: