在进行了20多年的Windows编程和两天的WPF后,我感觉自己什么也不懂 :-)
我的第一个WPF程序非常简单:您从资源管理器中拖放一些文件,并将它们的名称显示在TextBox控件中。 (对于ListBox,它可以正常工作,但这不是我想要的。当然,在Drop事件中手动添加行也可以 - 但我想学习绑定方式..)
所以我写了一个转换器,但不知何故它没有被使用(断点不会被命中),也没有显示任何内容。
这应该是一个小问题,或者我完全偏离了轨道。找到了许多类似的示例,我从中拼凑出了这个,但仍然无法使其正常工作。
(我可能不需要ConvertBack,但还是写下来了..)
这是转换器类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace WpTest02
{
public class ListToTextConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
StringBuilder sb = new StringBuilder();
foreach (string s in (List<string>)value) sb.AppendLine(s);
return sb.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string[] lines = ((string)value).Split(new string[] { @"\r\n" }, StringSplitOptions.RemoveEmptyEntries);
return lines.ToList<String>();
}
}
}
MainWindow.xaml,我怀疑绑定问题出在这里:
<Window x:Class="WpTest02.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpTest02"
Title="MainWindow" Height="350" Width="525"
>
<Window.Resources>
<local:ListToTextConverter x:Key="converter1" />
</Window.Resources>
<Grid >
<TextBox Name="tb_files" Margin="50,20,0,0" AllowDrop="True"
PreviewDragOver="tb_files_PreviewDragOver" Drop="tb_files_Drop"
Text="{Binding Path=fileNames, Converter={StaticResource converter1} }"
/>
</Grid>
</Window>
Codebehind文件只需绑定数据属性和拖放代码,就可以正常工作。
using System;
//etc ..
namespace WpTest02
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
fileNames = new List<string>();
}
public List<string> fileNames { get; set; }
private void tb_files_Drop(object sender, DragEventArgs e)
{
var files = ((DataObject)e.Data).GetFileDropList();
foreach (string s in files) fileNames.Add(s);
// EDIT: this doesn't help ? Wrong!
// EDIT: this is actually necessary! :
tb_files.GetBindingExpression(TextBox.TextProperty).UpdateTarget();
// this obviosly would work:
//foreach (string s in files) tb_files.Text += s + "\r\n";
}
private void tb_files_PreviewDragOver(object sender, DragEventArgs e)
{
e.Handled = true;
}
}
}
注意:我已经编辑了最后一段代码,强调了UpdateTarget
调用的重要性。