为毛不用数据绑定?
类似这样:
xmal:
[XML] 纯文本查看 复制代码 <Window x:Class="WpfApp1.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
xmlns:core="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<ObjectDataProvider x:Key="SexEnumKey" MethodName="GetValues" ObjectType="{x:Type core:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type Type="local:Sex"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Button Grid.Row="0" Name="Btn" Content="获取性别" Click="Btn_OnClick"></Button>
<DataGrid Grid.Row="1" Name="Dg" ItemsSource="{Binding}" CanUserAddRows="False" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridComboBoxColumn Header="性别" SelectedItemBinding="{Binding Sex}" ItemsSource="{Binding Source={StaticResource SexEnumKey}}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
后台代码:
[C#] 纯文本查看 复制代码 using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
namespace WpfApp1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
/// <summary>
///
/// </summary>
private readonly ObservableCollection<Customer> _data = new ObservableCollection<Customer>();
public MainWindow()
{
InitializeComponent();
_data.Add(new Customer {Sex = Sex.Man});
_data.Add(new Customer {Sex = Sex.Female});
Dg.DataContext = _data;
}
private void Btn_OnClick(object sender, RoutedEventArgs e)
{
var sex = _data.First().Sex.ToString();
MessageBox.Show(sex);
}
}
public class Customer
{
public Sex Sex { get; set; }
}
public enum Sex
{
[Description("男")] Man,
[Description("女")] Female
};
}
|