我有另一个WPF绑定问题。正当我想我已经弄清了这些东西时,我遇到了更多问题......:SWPF绑定问题 - UI更新,对象没有
无论如何...我已经创建了一个用于选择文件的自定义用户控件。这是一个简单的文本框,后面跟着一个网格中包含的按钮。我正在使用的控件的属性被称为FilePath,并且此控件上的TextBox绑定到该属性。点击按钮后,会打开一个SaveFileDialog,用户选择一个文件。在用户选择文件后,用户界面正确更新。
我似乎遇到的问题是,当我将一个对象绑定到控件(在这种情况下,我有一个具有DocumentFilePath属性的对象)时,对象不会在选择新文件时更新。
这里是我的用户控件中的相关代码:
public static readonly DependencyProperty FilePathProperty = DependencyProperty.Register("FilePath", typeof(string), typeof(FileSave), new UIPropertyMetadata(string.Empty, OnFilePathChanged));
public string FilePath
{
get
{
return this.GetValue(FilePathProperty) as string;
}
set
{
this.SetValue(FilePathProperty, value);
this.OnPropertyChanged("FilePath");
}
}
private void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
private static void OnFilePathChanged(object sender, DependencyPropertyChangedEventArgs e)
{
((FileSave)sender).OnPropertyChanged("FilePath");
}
而且用户控件编程用我的物体上反射添加到我的窗口:
private void AddFileSave(PropertyInfo pi)
{
FileSave fs = new FileSave();
Binding b = new Binding(pi.Name);
fs.SetBinding(FileSave.FilePathProperty, b);
this.AddToGrid(fs); //adds the control into my window's grid in the correct row and column; nothing fancy here
}
这可能是值得指出的是,如果我用现有的对象加载窗口,我的用户控件将正确显示,但仍不会在其绑定的对象内注册任何更改。
如果你们需要更多信息,请让我知道。
由于提前,
桑尼
编辑:我找到解决问题的方式,但是这可能不是一个很好的解决方案。通过仔细观察调试器,我发现当我在我的控件中设置FilePath属性时,对象被解除绑定。如果有人能够说明这一点,我会非常感激。在此同时,我已经改变了我开的SaveFileDialog代码看起来像这样:
private void Button_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
ofd.Multiselect = false;
ofd.Title = "Select document to import...";
ofd.ValidateNames = true;
ofd.ShowDialog();
if (this.GetBindingExpression(FilePathProperty) == null)
{
this.FilePath = ofd.FileName;
}
else //set value on bound object (THIS IS THE NEW PORTION I JUST ADDED)
{
BindingExpression be = this.GetBindingExpression(FilePathProperty);
string propName = be.ParentBinding.Path.Path;
object entity = be.DataItem;
System.Reflection.PropertyInfo pi = entity.GetType().GetProperty(propName);
pi.SetValue(entity, ofd.FileName, null);
}
if (!string.IsNullOrWhiteSpace(this.FilePath))
{
_fileContents = new MemoryStream();
using (StreamReader sr = new StreamReader(this.FilePath))
{
_fileContents = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(sr.ReadToEnd()));
}
}
else
{
_fileContents = null;
}
}
谢谢。那样做了。 – 2010-12-21 23:51:43