问题描述
我创建了一个UserControl
,它通过其ContentProperty
属性接收对象的集合,并通过为每个对象创建一个ContentControl
在屏幕上布置它们。在此示例中,这些对象是使事情变得简单的字符串,但是我的实际应用程序使用更复杂的对象和一些逻辑来选择适当的DataTemplates。布局也更复杂。
此屏幕截图显示了我的目标:
但是我得到了这个:
问题在于,MyControl
的每个实例都被分配了分配给它们的所有字符串,而不是每个实例都只获得了专门为其分配的字符串。
窗口代码:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:WpfApp1">
<StackPanel Orientation="Horizontal">
<local:MyControl Margin="10">
<sys:String>AAA</sys:String>
<sys:String>BBB</sys:String>
<sys:String>CCC</sys:String>
</local:MyControl>
<local:MyControl Margin="10">
<sys:String>DDD</sys:String>
<sys:String>EEE</sys:String>
<sys:String>FFF</sys:String>
</local:MyControl>
<local:MyControl Margin="10">
<sys:String>GGG</sys:String>
<sys:String>HHH</sys:String>
<sys:String>III</sys:String>
</local:MyControl>
</StackPanel>
</Window>
用户控件的代码:
[ContentProperty(nameof(MyProperty))]
public class MyControl : UserControl,IAddChild
{
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register(nameof(MyProperty),typeof(IList),typeof(MyControl),new PropertyMetadata(new List<object>()));
public IList MyProperty
{
get { return (IList)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty,value); }
}
public MyControl()
{
var sp = new StackPanel();
Content = sp;
Loaded += (_,__) =>
{
foreach (string e in MyProperty)
sp.Children.Add(new ContentControl { Content = e });
};
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)