WPF ListBox 将 ItemsSource 与 MVVM-light 绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18119900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:23:24  来源:igfitidea点击:

WPF ListBox bind ItemsSource with MVVM-light

c#wpfmvvmlistboxmvvm-light

提问by Misi

XAML

XAML

<Window x:Class="Html5Mapper.Mapper.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:wpt="http://schemas.xceed.com/wpf/xaml/toolkit"
    Title="HTML mapper" Height="300" Width="600" >
<Window.DataContext>
    <Binding Path="Main" Source="{StaticResource Locator}"/>
</Window.DataContext>

<ListBox Name="lbFiles" ItemsSource="{Binding Filescollection, Mode=OneWay}" Width="240" Height="220">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Margin="0,2">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="100" />
                    </Grid.ColumnDefinitions>
                    <Image Source="HTML.png" Height="40" Width="32" />
                    <TextBlock Grid.Column="1" Text="{Binding Name}" />
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

MainViewModel.cs

主视图模型.cs

public ObservableCollection<Files> Filescollection { get; set; }    
public MainViewModel()
{
    this.Filescollection = new ObservableCollection<Files>();
    SelectFilesAction();
}

private void SelectFilesAction()
{
   this.Filescollection.Add(new Files { Name = "index.html", Path = "C:\Files"});
   //lbFiles.ItemsSource = docs;
}

Q:What else do I need to get the docsobject into the Listbox ?

问:我还需要什么才能将docs对象放入 Listbox ?

回答by Vidas Vasiliauskas

In my opinion you are binding your controls to wrong datacontect, check output window for erros. You might want to set datacontext of main window to your MainViewModel (in codebehind or similar). Also why do you create another instance for docs? It is useless.

在我看来,您将控件绑定到错误的 datacontect,检查输出窗口是否存在错误。您可能希望将主窗口的数据上下文设置为您的 MainViewModel(在代码隐藏或类似中)。另外,为什么要为文档创建另一个实例?这是没用的。

public ObservableCollection<Files> Filescollection {get;set;}

public MainViewModel()
{
    this.Filescollection = new ObservableCollection<Files>();
    SelectFilesAction();
}

private void SelectFilesAction()
{
   Filescollection.Add(new Files { Name = "index.html", Path = "C:\Files"});
}

回答by JMK

Vidas is correct in that the DataContext of your Window is wrong, it needs to be your MainViewModel class.

Vidas 是正确的,因为您的 Window 的 DataContext 是错误的,它需要是您的 MainViewModel 类。

Get rid of this:

摆脱这个:

<Window.DataContext>
    <Binding Path="Main" Source="{StaticResource Locator}"/>
</Window.DataContext>

And add this to the Window tag:

并将其添加到 Window 标签:

<Window DataContext="{StaticResource MainViewModel}">

And that should do it.

那应该这样做。

回答by rgjais

<UserControl x:Class="RetailPOS.View.Usercontrols.MainWindow.Products"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
             mc:Ignorable="d" 
             xmlns:ctrl="clr-namespace:RetailPOS.View.Usercontrols.MainWindow"
             d:DesignHeight="200" d:DesignWidth="490" **DataContext="{Binding Source={StaticResource Locator}, Path=CategoryVM}"**
             xmlns:my="clr-namespace:WpfLab.Controls;assembly=WpfLab.Controls">
    <UserControl.Resources>
    </UserControl.Resources>
    <Grid Width="490" Height="360">
        <ListBox Name="LstProduct" ItemsSource="{Binding LstProduct}" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Orientation="Horizontal" Margin="0" Height="Auto" Width="490" >
                    </WrapPanel>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Button Margin="1" Content="{Binding Name}" Height="53" Background="{Binding Color}" HorizontalAlignment="Right" Width="79" 
                            Command="{Binding DataContext.ShowProductCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" 
                            CommandParameter="{Binding}">
                    </Button>                 
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

    </Grid>
</UserControl>

In the code behind

在后面的代码中

   private ObservableCollection<ProductDTO> _lstProduct;
   public ObservableCollection<ProductDTO> LstProduct
        {
            get { return _lstProduct; }
            set
            {
                _lstProduct = value;
                RaisePropertyChanged("LstProduct");
            }
        }

   /// <summary>
    /// Get all Commonly Used Products
    /// </summary>
    /// <returns>returns list of all Commonly Used  products present in database</returns>
private void FillCommonProducts()
{
    LstProduct = new ObservableCollection<ProductDTO>(from item in ServiceFactory.ServiceClient.GetCommonProduct() 
                               select item);
}