ListView将SelectedItem绑定到文本框

时间:2019-08-21 17:27:00

标签: c# wpf listview

我对绑定不熟悉,当我在RecipeName中选择一个项目时,我很难让我的ListView显示出来。

我正在尝试将所选项目绑定到我的TextBox。我确实可以将项目正确显示在ListView中,但是当我选择一个项目时,它不会在我的TextBox中预览。

我在这里做什么错了?

具有ListView和文本框的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));
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您没有使用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"
    />