新しい x:Bind を使用して ListView.SelectedItem をバインドしようとしています。私のコード:
意見:
//MainPage.xaml:
<Page
x:Class="BrokenListSample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:BrokenListSample"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="Beige">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<ListView Grid.Row="0" Background="LawnGreen"
ItemsSource="{x:Bind ViewModel.MyItems, Mode=OneWay}"
SelectedItem="{x:Bind ViewModel.BestItem, Mode=TwoWay}"
Width="300" Height="300"/>
<ListView Grid.Row="1" Background="LawnGreen"
ItemsSource="{Binding MyItems, Mode=OneWay}"
SelectedItem="{Binding BestItem, Mode=TwoWay}"
Width="300" Height="300"/>
</Grid>
分離コード:
//MainPage.xaml.cs:
using Windows.UI.Xaml.Controls;
namespace BrokenListSample
{
public sealed partial class MainPage : Page
{
public MainPageViewModel ViewModel { get; set; }
public MainPage()
{
InitializeComponent();
DataContextChanged += (s, e) => { ViewModel = DataContext as MainPageViewModel; };
DataContext = new MainPageViewModel();
}
}
}
そして最後に ViewModel:
//MainPageViewModel.cs:
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace BrokenListSample
{
public class MainPageViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private ObservableCollection<string> _myItems;
public ObservableCollection<string> MyItems
{
get { return _myItems; }
set { _myItems = value; OnPropertyChanged("MyItems"); }
}
private string _bestItem;
public string BestItem
{
get { return _bestItem; }
set { _bestItem = value; OnPropertyChanged("BestItem"); }
}
public MainPageViewModel()
{
MyItems = new ObservableCollection<string>() { "One", "Two", "Three", "Four" };
}
}
}
ご覧のとおり、MainPage に 2 つの ListView コントロールがあります。このコードを実行しようとしている場合は、確認したいバインディングの種類に応じて、いずれかをコメントしてください。2 行目の ListView は、古き良き Binding を使用していますが、これは単純に機能します。ここで驚きはありません。
サプライズには、StackOverflowException を引き起こしている新しい x:Bind を使用するものがあります。OneWay モードでは問題なく動作しますが、項目の 1 つをクリックするたびに TwoWay が StackOverflowException をスローします...陽気です...
私の質問は非常に単純です - 「なぜ、どのようにそれを解決するのですか?」