我创建了一个wpf DataGrid,它从文件名列表及其分数中调用。 网格工作正常,现在我试图让用户可以点击一行,它显示文件内容本身(文本文件)。 文本字符串非常大,因此我不希望它成为列表的属性。相反,我希望文件路径成为属性,只要我点击一行,流转化器就会读取文件。
我在c#中编码。到目前为止,这是我的(部分)代码:
public class DataLeakageScorer
{
public string fileName { get; set; }
public string score { get; set; }
public string path { get; set; }
public DataLeakageScorer(string fileName, string score, string path)
{
this.fileName = fileName;
this.score = score;
this.path = path;
}
}
和我的XAML:
<Grid>
<Button x:Name="button" Content="Browse" HorizontalAlignment="Left" Margin="464,22,0,0" VerticalAlignment="Top" Width="75" Click="browse"/>
<Label x:Name="status" Content="Please select a folder" FontSize="15" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" HorizontalAlignment="Center" Margin="0,5,121,0" VerticalAlignment="Top" Width="459" Height="52"/>
<DataGrid Name="scoresTable" AutoGenerateColumns="False" IsReadOnly="True" CanUserSortColumns="False" Margin="0,62,0,0">
<DataGrid.Columns>
<DataGridTextColumn Header="File Name" Binding="{Binding fileName}"/>
<DataGridTextColumn Header="Score" Binding="{Binding score}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
如果我不够清楚,谢谢你,对不起
答案 0 :(得分:0)
Here you have the answer.行详细信息是博客上你需要的东西吗?首先,您必须创建一个附加到DataGrid的自定义行为。我们称之为ReadFileBehavior。
它应该在将自身附加到DataGrid时订阅RowDetailsVisibilityChanged事件。
public class ReadFileBehavior : Behavior<DataGrid>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.RowDetailsVisibilityChanged += OnRowDetailsVisibilityChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.RowDetailsVisibilityChanged -= OnRowDetailsVisibilityChanged;
}
private void OnRowDetailsVisibilityChanged(object sender, DataGridRowDetailsEventArgs e)
{
var element = e.DetailsElement as TextBlock;
element.Text = File.ReadAllLines((element.DataContext as DataLeakageScorer).Path);
}
}
您可以在XAML中将行为添加到DataGrid:
<DataGrid ItemsSource="{Binding Customers}">
<Interactivity:Interaction.Behaviors>
<customBehaviors:ReadFileBehavior />
</Interactivity:Interaction.Behaviors>
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<TextBlock />
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
我还没有测试过这个解决方案,但可能需要将BindableBase继承添加到DataLeakageScorer(或实现INotifyPropertyChanged),因为您可能无权访问TextBlock.Text属性。比你只做这样的事情:
private void OnRowDetailsVisibilityChanged(object sender, DataGridRowDetailsEventArgs e)
{
var context = e.DetailsElement.DataContext as DataLeakageScorer
context.Score = File.ReadAllLines(context.Path);
}