[英]ListView binding SelectedItem to Textbox
我是绑定的新手,当我在ListView
选择一个项目时,我无法显示我的RecipeName
。
我试图将我选择的项目绑定到我的TextBox
。 我确实可以在ListView中正确显示我的项目,但是当我选择一个项目时,它不会在我的TextBox中预览。
我在这里做错了什么?
具有ListView和Textbox的Xaml
<ListView Grid.Column="0"
Name="listOfRecipes"
Margin="10,10,10,240"
Height="150"
ItemsSource="{Binding Path=Recipe}"
SelectedItem="{Binding Path=RecipeName, Mode=TwoWay}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=RecipeName, Mode=TwoWay}" /> // This lists my items in the ListView Correctly
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<TextBox Text="{Binding Path=RecipeName, Mode=TwoWay}" Grid.Column="1" Height="50" Margin="10,10,-10,340"/> // This doesn't preview the selected item.
我的课 :
public partial class ViewAll : Page, INotifyPropertyChanged
{
private Recipe _recipe;
public Recipe Recipe
{
get { return _recipe; }
set
{
if(_recipe != value)
{
_recipe = value;
OnPropertyChanged("Recipe");
}
}
}
public ViewAll()
{
InitializeComponent();
LoadItemTemplate();
}
public void LoadItemTemplate()
{
mrydendbEntities dbe = new mrydendbEntities();
listOfRecipes.ItemsSource = dbe.Recipe.ToList();
listOfRecipes.SelectedItem = dbe.Recipe.First();
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
您没有使用ItemsSource绑定来填充列表视图; 这样做是在Visual Studio的“输出”窗格中生成错误。 所以我省略了。 如果将某些东西绑定到ItemsSource,则“某物”必须是对象的集合,而不是诸如Page的Recipe
属性之类的单个对象。
我猜想,当用户单击列表视图中的“ Recipe
”时,您希望将该Recipe
分配给页面的“ Recipe
属性。 一旦知道了,就可以将TextBox的Text绑定到该配方的属性。
<ListView Grid.Column="0"
Name="listOfRecipes"
Margin="10,10,10,240"
Height="150"
SelectedItem="{Binding Recipe, RelativeSource={RelativeSource AncestorType=Page}}
>
<!-- snip -->
<TextBox
Text="{Binding Recipe.Name, RelativeSource={RelativeSource AncestorType=Page}}"
Grid.Column="1"
Height="50"
Margin="10,10,-10,340"
/>
这是另一种方法。
<TextBox
Text="{Binding SelectedItem.Name, ElementName=listOfRecipes}"
Grid.Column="1"
Height="50"
Margin="10,10,-10,340"
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.