ListView双向编译绑定(x:Bind)

时间:2015-06-04 15:14:07

标签: c# xaml listview binding windows-10

我想显示几个名字,我希望它们可以编辑。 所以我使用了一个ObservableColection,并使用新的x:Bind功能将它绑定到ListView。

这是我的XAML:

    <ListView>
        <ListView ItemsSource="{x:Bind ViewModel.Players}">
                <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch" />
            </Style>
        </ListView.ItemContainerStyle>

        <ListView.ItemTemplate>
            <DataTemplate xmlns:model="using:Flechette.Model"  x:DataType="model:Player">
                <TextBox Text="{x:Bind Name, Mode=TwoWay}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

我的代码背后:

public sealed partial class GameSettingsPage : Page
{
    ViewModel.GameSettingsViewModel ViewModel { get; set; }

    public GameSettingsPage()
    {
        InitializeComponent();
        DataContextChanged += (s, e) => ViewModel = DataContext as ViewModel.GameSettingsViewModel;
    }
}

问题是TwoWay绑定无法编译,我收到错误 CS1061&#39; WeakReference&#39;不包含&#39; LostFocus&#39;的定义没有扩展方法&#39; LostFocus&#39;接受类型&#39; WeakReference&#39;的第一个参数。可以找到(你错过了使用指令或汇编引用吗?)

我该如何解决?

1 个答案:

答案 0 :(得分:0)

这似乎是Windows 10 SDK预览版中的一个问题。给出以下代码:

<强> MainPage.xaml中:

     <ListView x:Name="Players">
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch" />
            </Style>
        </ListView.ItemContainerStyle>

        <ListView.ItemTemplate>
            <DataTemplate x:DataType="local:Player">
                <TextBox Text="{x:Bind Name, Mode=TwoWay}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

<强> MainPage.xaml.cs中:

    private ObservableCollection<Player> players = new ObservableCollection<Player>();
    public MainPage()
    {
        this.InitializeComponent();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        this.players.Add(new Player());
        this.players.Add(new Player());
        this.players.Add(new Player());
        this.players.Add(new Player());
        this.players.Add(new Player());

        this.Players.ItemsSource = players;
    }

<强> Player.cs:

public class Player : INotifyPropertyChanged
{
    private string name;

    public string Name
    {
        get { return name; }
        set
        {
            if (value == name) return;
            name = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

编译和应用程序有效并提供预期的行为:

Working app