簡體   English   中英

WPF MVVM ComboBox數據綁定

[英]WPF MVVM ComboBox data binding

我正在嘗試創建一個簡單的WPF應用程序並將數據綁定到組合框,但是我沒有任何運氣。 我的PeriodList可以很好地填充,但是沒有綁定到組合框。 我是否需要在XAML或后面的代碼中設置DataContext? 請幫助,我很困惑。

這是我的XAML

<UserControl x:Class="FinancialControlApp.KeyClientReportView"
             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:local="clr-namespace:FinancialControlApp"
             mc:Ignorable="d" 
             d:DesignHeight="300" Width="630">

    <UserControl.Resources>
        <!-- DataTemplate (View) -->
        <DataTemplate DataType="{x:Type local:KeyClientReportModel}">
        </DataTemplate>
    </UserControl.Resources>

    <DockPanel Margin="20">
        <DockPanel DockPanel.Dock="Top" VerticalAlignment="Center">
            <TextBlock Margin="10,2" DockPanel.Dock="Left" Text="Start Period" VerticalAlignment="Center" />

            <ComboBox Name="cmbStartPeriod" Margin="10,2" Width="112" VerticalAlignment="Center" ItemsSource="{Binding PeriodList}">
            </ComboBox>

            <TextBlock Margin="10,2" DockPanel.Dock="Left" Text="End Period" VerticalAlignment="Center" />

            <ComboBox Name="cmbEndPeriod" Margin="10,2" Width="112" VerticalAlignment="Center" ItemsSource="{Binding PeriodList}" />

            <!--<Button Content="Save Product" DockPanel.Dock="Right" Margin="10,2" VerticalAlignment="Center"
                        Command="{Binding Path=SaveProductCommand}" Width="100" />-->

            <Button Content="Run" DockPanel.Dock="Left" Margin="10,2" 
                        Command="{Binding Path=GetProductCommand}" IsDefault="True" Width="100" />
        </DockPanel>

        <!--<ContentControl Margin="10" Content="{Binding Path=PeriodName}" />-->
        <ContentControl Margin="10"></ContentControl>
    </DockPanel>
</UserControl>

這是我的模特

     namespace FinancialControlApp
    {
       public class KeyClientReportModel : ObservableObject
       {

        private string _periodName;

        public string PeriodName
        {
            get { return _periodName; }
            set
            {
                if (value != _periodName)
                {
                    _periodName = value;
                    OnPropertyChanged("PeriodName");
                }
            }
        }

        List<KeyClientReportModel> _periodList = new List<KeyClientReportModel>();

        public List<KeyClientReportModel> PeriodList
        {
            get { return _periodList; }
            set
            {
                _periodList = value;
                OnPropertyChanged("PeriodList");
            }
        }
      }
}

這是我的ViewModel

    namespace FinancialControlApp
{
    public class KeyClientReportViewModel : ObservableObject, IPageViewModel
    {
        private KeyClientReportModel _currentPeriod;
        private ICommand _getReportCommand;
        private ICommand _saveReportCommand;

        public KeyClientReportViewModel()
        {
            GetPeriod();
        }

        public string Name
        {
            get { return "Key Client Report"; }
        }

        public ObservableCollection<KeyClientReportModel> _periodName;
        public ObservableCollection<KeyClientReportModel> PeriodName
        {
            get { return _periodName; }
            set
            {
                if (value != _periodName)
                {
                    _periodName = value;
                    OnPropertyChanged("PeriodName");
                }
            }
        }

        private void GetPeriod()
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            Helper_Classes.SQLHelper helper = new Helper_Classes.SQLHelper();

            ds = helper.getPeriod();
            dt = ds.Tables[0];
            PeriodName = new ObservableCollection<KeyClientReportModel>();
            foreach (DataRow dr in dt.Rows)
            {
                var period = dr["Period"].ToString();
                if (period != null)
                {
                    PeriodName.Add(new KeyClientReportModel { PeriodName = period });
                }
                //p.PeriodName = dr["Period"].ToString();           
            }
        }
}
}

更新:因此,我附加了一個值轉換器以插入調試器,這就是我看到的內容。 我懂了

我在清單中看到5個項目

更改

ItemsSource="{Binding KeyClientReportModel.PeriodList}"

至:

ItemsSource="{Binding PeriodList}"

確保將ViewModel設置為視圖的DataContext屬性。

將組合框DisplayMemberPath設置為KeyClientReportViewModel類的屬性Name

或者,可以替代KeyClientReportViewModel類內部的.ToString()方法,以提供Combobox項的顯示文本。

這可以幫助你

- - - 視圖

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        <!-- To get the ViewModel -->
        xmlns:viewmodels="clr-namespace:WpfApp1.ViewModels"
        Title="MainWindow">
    <Window.DataContext>
        <!-- Assigning the ViewModel to the View -->
        <viewmodels:MainWindowViewModel />
    </Window.DataContext>
    <DockPanel VerticalAlignment="Center"
               DockPanel.Dock="Top">
        <TextBlock Margin="10,2"
                   VerticalAlignment="Center"
                   DockPanel.Dock="Left"
                   Text="Start Period" />
        <ComboBox Name="cmbStartPeriod"
                  Width="112"
                  Margin="10,2"
                  VerticalAlignment="Center"
                  ItemsSource="{Binding PeriodName}" // Items in the ViewModel 
                  DisplayMemberPath="Name"/> // Property to display
    </DockPanel>
</Window>

------- ViewModel

public class MainWindowViewModel
{
    public MainWindowViewModel()
    {
        var items = new List<KeyClientReportModel>
        {
            new KeyClientReportModel
            {
                Name = "First",
                Value = 1
            },
            new KeyClientReportModel
            {
                Name = "Second",
                Value = 1
            }
        };

        PeriodName = new ObservableCollection<KeyClientReportModel>(items);
    }

    // You don't need to notify changes here because ObservableCollection 
    // send a notification when a change happens. 
    public ObservableCollection<KeyClientReportModel> PeriodName { get; set; }

}

public class KeyClientReportModel
{
    public int Value { get; set; }
    public string Name { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM