我在让我的用户控件绑定(bind)到列表<>时遇到了一些麻烦。当我尝试做类似的事情时效果很好:
public string Map
{
get { return (string)GetValue(MapProperty); }
set
{
SetValue(MapProperty, value);
}
}
public static readonly DependencyProperty MapProperty =
DependencyProperty.Register(
"Map",
typeof(string),
typeof(GamePane),
new PropertyMetadata(
"Unknown",
ChangeMap)
);
但是,如果我尝试使用除字符串、整数或 float 以外的属性,我会得到“无法识别或无法访问成员‘属性名称’”。示例:
public List<string> Players
{
get { return (List<string>)GetValue(PlayersProperty); }
set
{
SetValue(PlayersProperty, value);
}
}
public static readonly DependencyProperty PlayersProperty =
DependencyProperty.Register(
"Players",
typeof(List<string>),
typeof(GamePane),
new PropertyMetadata(
new List<string>(),
ChangePlayers)
);
除了类型之外,代码完全相同。
我发现我可能需要使用 BindableList,但是,对于 Windows 8 项目,这似乎不存在。
谁能给我指出正确的方向或告诉我另一种方法。
编辑:根据请求,我的 ListView 的 XAML,我尝试将字符串列表绑定(bind)到:
<ListView x:Name="PlayerList" SelectionMode="None" ScrollViewer.HorizontalScrollMode="Disabled" ScrollViewer.VerticalScrollMode="Disabled" ItemsSource="{Binding Players}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Disabled" Margin="6,-1,0,0" IsHitTestVisible="False">
然后,在我的主视图中,我绘制了我的 GridView,它创建了我的绑定(bind)并且有异常:
<GridView
x:Name="currentGames"
AutomationProperties.AutomationId="ItemsGridView"
AutomationProperties.Name="Items"
TabIndex="1"
Padding="12,0,12,0"
ItemsSource="{Binding Source={StaticResource itemsViewSource}}"
SelectionMode="None"
IsSwipeEnabled="false" Grid.Row="1" Margin="48,-20,0,0" Height="210" VerticalAlignment="Top" >
<GridView.ItemTemplate>
<DataTemplate>
<local:GamePane Map="{Binding Map}" Time="{Binding TimeRemaining}" Players="{Binding Players}"/>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
有趣的是,虽然此 XAML 破坏了 Visual Studio 和 Blend 的设计器,但代码仍会执行。尽管如此,我的玩家不会出现。
最佳答案
是的,它有效。
这是绑定(bind)到它的 XAML:
<Grid Background="Black">
<local:MyUserControl x:Name="MyControl" />
<ListBox ItemsSource="{Binding MyList, ElementName=MyControl}" />
</Grid>
这是用户控制代码:
public sealed partial class MyUserControl : UserControl
{
public MyUserControl()
{
this.InitializeComponent();
}
public string[] MyList
{
get { return new string[] { "One", "Two", "Three" }; }
}
}
关于c# - 将列表绑定(bind)到 UserControl 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12947694/