支持.Net/.Net Core/.Net Framework,可以部署在Docker, Windows, Linux, Mac。 Redis作為一款主流的緩存工具在業內已廣受歡迎。本文將會介紹操作Redis的一種最簡單的方法。 本文假定你身邊已有安裝好的Redis應用,該應用的網路地址為(ip+p ...
WPF入門教程系列目錄 WPF入門教程系列二——Application介紹 WPF入門教程系列三——Application介紹(續) WPF入門教程系列四——Dispatcher介紹 WPF入門教程系列十一——依賴屬性(一) WPF入門教程系列十五——WPF中的數據綁定(一) 接上文WPF入門教程系列二十八 ——DataGrid使用示例MVVM模式(6)
13.通過Command指令,傳遞了下拉框所選擇的省份,datagrid自動顯示相應省份的城市信息,但是以上示例中有一個Bug,就是下拉框中綁定的數據無法顯示。
這是由於DataGridComboBoxColumn若要填充下拉列表,請先使用以下選項之一設置 ItemsSource 屬性 ComboBox :
1)靜態資源。 使用StaticResource 標記擴展。
2)x:Static 代碼實體。 使用x:Static 標記擴展。
3)類型的內聯集合 ComboBoxItem 。
14.比較適合的綁定方式是 2)x:Static 代碼實體。 使用x:Static 標記擴展需要添加相應的命名空間。在Visual Studio 2022中打開MainWindows.xmal文件,併在文件的開頭添加如下命名空間。
xmlns:v="clr-namespace:WpfGridDemo.NET7.ViewModel"
15. 在Visual Studio 2022中打開MainWindows.xmal文件。對DataGridComboBoxColumn的ItemsSource進行了數據綁定。具體代碼如下:
<DataGridComboBoxColumn Header="城市" Width="120" x:Name="cboCity"
ItemsSource="{x:Static v:MainWindowVM.GridCityList}"
ClipboardContentBinding="{x:Null}" SelectedValuePath="Code"
SelectedValueBinding="{Binding Path=CityCode,UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="Name" SelectedItemBinding="{x:Null}" />
16.在Visual Studio 2022的解決方案資源管理器中,找到MainWindowVM.cs文件,將GridCityList屬性改為靜態屬性,用於綁定DataGridComboBoxColumn的ItemsSource。具體如下代碼:
private static ObservableCollection<City> cityList;
public static ObservableCollection<City> GridCityList
{
get { return cityList; }
set
{
cityList = value;
new ViewModelBase().RaisePropertyChanged("GridCityList");
}
}
17.在Visual Studio 2022中按F5鍵,啟動WPF應用程式。然後使用滑鼠點擊省份下拉框,能夠看到,界面中DataGrid中的數據,隨著下拉框的變化而隨之變化,但是城市下拉框中卻沒有任何數據。看來綁定失效了。如下圖。
18. 使用靜態代碼實體的方式,實現省市縣聯動失敗了。又不想使用其他兩種方式。在一陣猛於虎的搜索之後,發現一種實現方式。在Visual Studio 2022中打開MainWindows.xmal文件。對DataGridComboBoxColumn進行了數據綁定。具體代碼如下:
<DataGridComboBoxColumn Header="城市(Style)" SelectedValuePath="Code"
SelectedValueBinding="{Binding Path=CityCode,UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="Name" SelectedItemBinding="{x:Null}" Width="1*">
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource"
Value="{Binding Path=DataContext.GridCity,ElementName=gridArea}" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource"
Value="{Binding Path=DataContext.GridCity,ElementName=gridArea}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
</DataGridComboBoxColumn>
19.在Visual Studio 2022的解決方案資源管理器中,找到MainWindowVM.cs文件,添加一個GridCity屬性,用於綁定DataGridComboBoxColumn的ItemsSource。以下是屬性代碼,更完整的代碼,請參見下麵類的完整代碼。
private ObservableCollection<City> listCity;
public ObservableCollection<City> GridCity
{
get { return listCity; }
set
{
listCity = value;
RaisePropertyChanged("GridCity");
}
}
20.MainWindow.xmal的全部代碼如下:
<Window x:Class="WpfGridDemo.NET7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:be="http://schemas.microsoft.com/xaml/behaviors"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfGridDemo.NET7"
xmlns:v="clr-namespace:WpfGridDemo.NET7.ViewModel"
mc:Ignorable="d"
Title="MainWindow" Height="600" Width="960" Loaded="Window_Loaded" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="25"></RowDefinition>
</Grid.RowDefinitions>
<WrapPanel Grid.Row="0" HorizontalAlignment="Left">
<ComboBox x:Name="cboProvince" DisplayMemberPath="Name" SelectedValuePath="Code" >
<be:Interaction.Triggers>
<be:EventTrigger EventName="SelectionChanged">
<be:InvokeCommandAction Command="{Binding ProviceChangedAction}"
CommandParameter="{Binding ElementName=cboProvince}"/>
</be:EventTrigger>
</be:Interaction.Triggers>
</ComboBox>
</WrapPanel>
<DataGrid x:Name="gridArea" Grid.Row="1" ItemsSource="{Binding GridAreaList}"
AutoGenerateColumns="False" HorizontalAlignment="Left" VerticalAlignment="Top"
SelectedItem="{Binding Path=AreaVM,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
<DataGrid.Columns>
<DataGridComboBoxColumn Header="城市" Width="120" x:Name="cboCity"
ItemsSource="{x:Static v:MainWindowVM.GridCityList}"
ClipboardContentBinding="{x:Null}" SelectedValuePath="Code"
SelectedValueBinding="{Binding Path=CityCode,UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="Name" SelectedItemBinding="{x:Null}" />
<DataGridComboBoxColumn Header="城市(Style)" SelectedValuePath="Code"
SelectedValueBinding="{Binding Path=CityCode,UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="Name" SelectedItemBinding="{x:Null}" Width="1*">
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource"
Value="{Binding Path=DataContext.GridCity,ElementName=gridArea}" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource"
Value="{Binding Path=DataContext.GridCity,ElementName=gridArea}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
</DataGridComboBoxColumn>
<DataGridTextColumn Header="縣區鎮" Width="*"
Binding="{Binding Name}" ClipboardContentBinding="{x:Null}"/>
<DataGridTextColumn Header="郵編" Width="100"
Binding="{Binding Code}" ClipboardContentBinding="{x:Null}"/>
<DataGridTextColumn Header="創建時間" Width="160"
Binding="{Binding Created}" ClipboardContentBinding="{x:Null}"/>
<DataGridTextColumn Header="更新時間" Width="160"
Binding="{Binding Updated}" ClipboardContentBinding="{x:Null}"/>
</DataGrid.Columns>
</DataGrid>
<WrapPanel Grid.Row="2">
<Button x:Name="btnRefresh" Height="22" Width="120" Click="btnRefresh_Click">刷新</Button>
<Button x:Name="btnSave" Height="22" Width="120" Command="{Binding ClickSaveAction}" >保存</Button>
</WrapPanel>
</Grid>
</Window>
21. MainWindowsVM類的完整代碼,如下:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.DirectoryServices.ActiveDirectory;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using WpfGridDemo.NET7.Entitys;
namespace WpfGridDemo.NET7.ViewModel
{
public class MainWindowVM: ViewModelBase
{
public MainWindowVM() {
cityList = new ObservableCollection<City>();
areaList = new ObservableCollection<Area>();
listCity = new ObservableCollection<City>();
}
private Area m_Area;
/// <summary>
/// 縣鎮區數據
/// </summary>
public Area AreaVM
{
get { return m_Area; }
set { m_Area = value; }
}
private string m_Province_Code;
/// <summary>
/// 省--代碼
/// </summary>
public string ProvinceCode { get => m_Province_Code; set => m_Province_Code = value; }
private ObservableCollection<Area> areaList;
public ObservableCollection<Area> GridAreaList
{
get { return areaList; }
set
{
areaList = value;
RaisePropertyChanged("GridAreaList");
}
}
private static ObservableCollection<City> cityList;
public static ObservableCollection<City> GridCityList
{
get { return cityList; }
set
{
cityList = value;
new ViewModelBase().RaisePropertyChanged("GridCityList");
}
}
private ObservableCollection<City> listCity;
public ObservableCollection<City> GridCity
{
get { return listCity; }
set
{
listCity = value;
RaisePropertyChanged("GridCity");
}
}
/// <summary>
/// 命令要執行的方法
/// </summary>
void SaveExecute()
{
try
{
GridDbContext db = new GridDbContext();
var list=db.Area.AsTracking().ToList();
Area modifyArea = list.Where(x=>x.Id==AreaVM.Id).FirstOrDefault();
if (modifyArea != null)
{
modifyArea.Name = AreaVM.Name;
modifyArea.Updated = DateTime.Now;
db.SaveChanges();
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 命令是否可以執行
/// </summary>
/// <returns></returns>
bool CanSaveExecute()
{
return false;
}
/// <summary>
/// 創建新命令
/// </summary>
public ICommand ClickSaveAction
{
get
{
return new Command.SaveCommand(SaveExecute, CanSaveExecute);
}
}
//combobox
/// <summary>
/// 命令要執行的方法
/// </summary>
void ProviceSelectionChangedExecute(object sender)
{
try
{
if (sender is ComboBox)
{
ComboBox drp=sender as ComboBox;
ProvinceCode=drp.SelectedValue.ToString();
GridDbContext db = new GridDbContext();
var list = db.City.AsTracking().ToList();
List<City> citys = list.Where(x => x.ProvinceCode == ProvinceCode).ToList();
var cityCodes = from city in citys
select city.Code;
List<Area> areas = db.Area.AsTracking().ToList()
.Where(x => cityCodes.Contains(x.CityCode)).ToList();
areaList.Clear();
if (areas!=null)
{
areas.ForEach((t) =>
{ areaList.Add(t); }
);
}
cityList.Clear();
if (citys != null)
{
citys.ForEach((t) =>
{ cityList.Add(t); }
);
}
listCity.Clear();
if (citys != null)
{
citys.ForEach((t) =>
{ listCity.Add(t); }
);
}
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 命令是否可以執行
/// </summary>
/// <returns></returns>
bool CanSelectionChangedExecute()
{
return true;
}
/// <summary>
/// 創建新命令
/// </summary>
public ICommand ProviceChangedAction
{
get
{
return new Command.ProvinceChangedCommand<object>(ProviceSelectionChangedExecute
, CanSelectionChangedExecute);
}
}
}
}
22.在Visual Studio 2022中按F5鍵,啟動WPF應用程式。然後使用滑鼠點擊省份下拉框,能夠看到,界面中DataGrid中的數據,隨著下拉框的變化而隨之變化,其中使用靜態實體代碼綁定的城市下拉框中卻沒有任何數據。使用使用非靜態資源,在<DataGridComboBoxColumn.EditingElementStyle>與 <DataGridComboBoxColumn.ElementStyle>兩個樣式中綁定combobox的itemSource屬性方式,效果有效。如下圖。