[英]UserControl with Dependency Property inside an ItemsControl: how to Bind element of ItemSource to x:Name of UserControl?
My class IFrame can contain other IFrames: 我的IFrame类可以包含其他IFrame:
public interface IFrame
{
int Id { get; }
string Summary { get; }
BindableCollection<IFrame> SubFrames { get; set; }
}
To present an IFrame, I have a custom UserControl: 为了展示一个IFrame,我有一个自定义的UserControl:
<UserControl x:Class="Views.FrameView"
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:Views="clr-namespace:Views"
mc:Ignorable="d"
x:Name="FrameXName">
<StackPanel Orientation="Horizontal">
<Label Content="{Binding ElementName=FrameXName, Path=Id}" Width="50"/>
</StackPanel>
</UserControl>
With codebehind: 与代码隐藏:
public partial class FrameView : UserControl
{
public FrameView()
{
InitializeComponent();
}
public static DependencyProperty IdProperty = DependencyProperty.Register(
"Id", typeof(int), typeof(FrameView));
public int Id
{
get { return (int) GetValue(IdProperty); }
set { SetValue(IdProperty, value); }
}
}
And thus I can display a Frame in a FooView.xaml using: <Views:FrameView x:Name="Frame1" Width="50" Height="50"/>
IF I define the following in FooViewModel.cs: public IFrame Frame1 { get { return Frames.ElementAt(1); } }
因此,我可以使用以下命令在FooView.xaml中显示框架:
<Views:FrameView x:Name="Frame1" Width="50" Height="50"/>
IF我在FooViewModel.cs中定义了以下内容: public IFrame Frame1 { get { return Frames.ElementAt(1); } }
public IFrame Frame1 { get { return Frames.ElementAt(1); } }
My Goal: 我的目标:
I want to have a FrameView displayed for every IFrame in a collection, for example: 我想为集合中的每个IFrame显示一个FrameView,例如:
<ItemsControl ItemsSource="{Binding Frames}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Views:FrameView x:Name="{Binding}" Width="50" Height="50"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Where public BindableCollection<IFrame> Frames
is defined. 其中定义了
public BindableCollection<IFrame> Frames
。
Unfortunately, this does not work, the compiler says MarkupExtensions are not allowed for Uid or Name property values, so '{Binding}' is not valid.
不幸的是,这是行不通的,编译器说
MarkupExtensions are not allowed for Uid or Name property values, so '{Binding}' is not valid.
How can I achieve my goal? 我如何实现我的目标? Many thanks in advance.
提前谢谢了。
In your datatemplate you can replace 在您的数据模板中,您可以替换
<Views:FrameView x:Name="{Binding}" Width="50" Height="50" />
with 与
<Views:FrameView Id="{Binding Path=Id}" Width="50" Height="50" />
should work fine 应该工作正常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.