DataGridTemplate列,文本框不保留datagrid列字段中的值

时间:2013-09-26 10:54:03

标签: c# wpf c#-4.0 wpfdatagrid

我想要一个只包含10个字符作为最大长度的文本。当我发现普通的Datagrid文本列没有maxlength属性时,我选择了Template列。但是对于下面的xaml代码。数据未保存回绑定字段并显示旧值。任何人都可以伸出援助之手。

    <Grid Background="#FFF0F0F0">
        <DataGrid AlternatingRowBackground="#FFE9FFE9" AlternationCount="1" AutoGenerateColumns="False" PreviewKeyDown="DgvDiagramNo_PreviewKeyDown" CanUserAddRows="False" CanUserResizeColumns="False" ColumnHeaderHeight="30" DataContext="{Binding}" Height="482" ItemsSource="{Binding Path=., Mode=TwoWay}" Margin="23,59,0,0" Name="DgvDiagramNo" OverridesDefaultStyle="False" RowHeaderWidth="0" RowHeight="30" ScrollViewer.VerticalScrollBarVisibility="Auto" SelectionMode="Single" SelectionUnit="FullRow" UseLayoutRounding="True" VerticalAlignment="Top" HorizontalAlignment="Left" Width="958" DataGridCell.Selected="DataGrid_select" CanUserReorderColumns="False" CellStyle="{StaticResource Body_Content_DataGrid_Centering}"  KeyUp="DgvDiagramNo_KeyUp" BeginningEdit="DgvDiagramNo_BeginningEdit" CellEditEnding="DgvDiagramNo_CellEditEnding" Sorting="DgvDiagramNo_Sorting">
            <DataGrid.Columns>
<DataGridTemplateColumn Header="売価" Width="150" MinWidth="100" MaxWidth="100" >
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding Path= SellingPrice, Mode=TwoWay}"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                        <DataGridTemplateColumn.CellEditingTemplate >
                            <DataTemplate>
                                <TextBox MaxLength="10"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellEditingTemplate>
                    </DataGridTemplateColumn>

        

1 个答案:

答案 0 :(得分:2)

您忘记了{Binding}

TextBox中的CellEditingTemplate
<DataGridTemplateColumn Header="売価" Width="150" MinWidth="100" MaxWidth="100" >
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding SellingPrice}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate >
        <DataTemplate>
            <TextBox MaxLength="10" Text="{Binding SellingPrice}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

编辑:使用以下视图模型成功测试

public class RowViewModel
{
    public string SellingPrice { get; set; }
}

public class ViewModel
{
    public ViewModel()
    {
        Rows = new ObservableCollection<RowViewModel>
        {
              new RowViewModel { SellingPrice = "123" },
              new RowViewModel { SellingPrice = "456" }, 
        };
    }

    public IEnumerable<RowViewModel> Rows { get; set; }
}