【发布时间】:2014-06-03 20:39:51
【问题描述】:
经过 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 调用的重要性。
【问题讨论】:
标签: c# wpf binding textbox ivalueconverter