繁体   English   中英

将List绑定到UserControl属性

[英]Binding a List to a UserControl Property

我将用户控件绑定到List <>时遇到了一些麻烦。 当我尝试做类似的事情时它很有效:

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等,我会得到“成员'属性名'无法识别或无法访问”。 例:

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:

<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" }; }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM