如果我尝试这样做,我会得到" System.Windows.Markup.XamlParseException "。
我的XAML代码如下所示:
<Window x:Class="WpfApplication1.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"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid ItemsSource="{Binding ErrorLog}" AutoGenerateColumns="False" IsReadOnly="True" CanUserAddRows="False" CanUserDeleteRows="False">
<DataGrid.Columns>
<!-- This is working -->
<DataGridTextColumn Binding="{Binding}" Header="Fehler" Width="*"/>
<!-- This is not working -->
<DataGridTemplateColumn Header="">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding}" AcceptsReturn="True" AcceptsTab="True" TextWrapping="Wrap"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
代码背后的代码如下所示:
using System.Collections.ObjectModel;
using System.Windows;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
public ObservableCollection<string> ErrorLog { get; set; } = new ObservableCollection<string>()
{
"A",
"B"
};
}
}
答案 0 :(得分:1)
来自例外的其他信息是:双向绑定需要Path或XPath。
TextBox Text属性默认具有TwoWay绑定模式。 TwoWay绑定不接受"{Binding}"
之类的空绑定。请尝试以下方法。
<DataGridTemplateColumn Header="">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=.}" AcceptsReturn="True" AcceptsTab="True" TextWrapping="Wrap"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
我认为,更改您的集合类型并使用一些自定义类型而不是字符串将是一个更好的解决方案: 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>
代码隐藏:
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; }
}
另外考虑实现INotifyPropertyChanged接口,以便在需要时能够从视图模型中更改消息。