Binding a string list to a DataGridTemplateColumn TextBox

前端 未结 1 1743
[愿得一人]
[愿得一人] 2021-01-29 02:38

If I try to do that, I get \"System.Windows.Markup.XamlParseException\".

My XAML code looks like this:



        
相关标签:
1条回答
  • 2021-01-29 03:08

    Additional information from exception is: Two-way binding requires Path or XPath. TextBox Text property has TwoWay binding mode by default. TwoWay bindings do not accept empty bindings like "{Binding}". Try the following.

    <DataGridTemplateColumn Header="">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <TextBox Text="{Binding Path=.}" AcceptsReturn="True" AcceptsTab="True" TextWrapping="Wrap"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    

    I think, changing your collection type and using some custom type instead of string will be a better solution though: XAML:

    <Grid>
        <DataGrid ItemsSource="{Binding ErrorLog}" AutoGenerateColumns="False" IsReadOnly="True" CanUserAddRows="False" CanUserDeleteRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Message}" Header="Fehler" Width="*"/>
                <DataGridTemplateColumn Header="">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox Text="{Binding Message}" AcceptsReturn="True" AcceptsTab="True" TextWrapping="Wrap"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
    

    Code-behind:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new MainViewModel();
        }
    }
    
    public class MainViewModel
    {
        public ObservableCollection<Error> ErrorLog { get; set; } = new ObservableCollection<Error>
                                                                        {
                                                                            new Error("A"),
                                                                            new Error("B"),
                                                                        };
    }
    
    public class Error
    {
        public Error(string message)
        {
            Message = message;
        }
    
        public string Message { get; set; }
    }
    

    Also consider implement INotifyPropertyChanged interface to be able to change message from view model if needed.

    0 讨论(0)
提交回复
热议问题