遇到的问题
- 最开始找到的例子要写 Convert, 感觉和 Vue-Elment 的差别比较大后面找到类似与 Vue-Element UI 的写法,
- 开始时数值不更新
关键代码
Xaml
<DataGridTemplateColumn Header="Digit" Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
ItemsSource="{Binding DataContext.DigitTypes, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
SelectedValue="{Binding DigitType,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="Id"
DisplayMemberPath="Name"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
完整代码
CSharp
public class EnumDesp
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MainWindowViewModel : BindableBase
{
private string _title = "Prism Application";
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
public ObservableCollection<RealDigitViewModel> Digits { get; set; }=new ObservableCollection<RealDigitViewModel>();
public ObservableCollection<EnumDesp> DigitTypes { get; set; }
public MainWindowViewModel()
{
DigitTypes = DigitTypeConverter.DigitTypes;
this.Digits.Add(new RealDigitViewModel()
{
Name = "Abc",
DigitType = 1
});
this.Digits.Add(new RealDigitViewModel()
{
Name = "Def",
DigitType = 2
});
}
}
xmal
<Window x:Class="BlankApp1.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
Title="{Binding Title}" Height="350" Width="525" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Button Grid.Row="0" Command="{Binding MyCommand}" Content="Me" ></Button>
<DataGrid Grid.Row="1" ItemsSource="{Binding Digits}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTemplateColumn Header="Digit" Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
ItemsSource="{Binding DataContext.DigitTypes, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
SelectedValue="{Binding DigitType,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="Id"
DisplayMemberPath="Name"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>