【问题标题】:Binding a List to a UserControl Property将列表绑定到 UserControl 属性
【发布时间】:2012-10-08 12:00:47
【问题描述】:

我在让我的用户控件绑定到列表 时遇到了一些麻烦。当我尝试执行以下操作时效果很好:

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)
    );

但是,如果我尝试使用比字符串、int 或 float 等更多的属性,我会得到“成员 'Property Name' 无法识别或不可访问”。示例:

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 项目,这似乎不存在。

谁能指出我正确的方向或告诉我另一种方法。

编辑:根据请求,我的列表视图的 XAML,我尝试将字符串列表绑定到:

<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,它创建了我的 Bindings 并且有异常:

<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 的设计器,但代码仍将执行。不过,我的玩家不会出现。

【问题讨论】:

  • 您能否也发布您尝试绑定到该属性的 XAML?
  • 我已经从我的 MainPage 和 UserControl 发布了 XAML,用于处理我遇到的绑定问题。

标签: c# xaml data-binding user-controls windows-8


【解决方案1】:

是的,它有效。

这是要绑定到它的 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" }; }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多