[英]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.