[英]WPF: How to bind the result of an OpenFileDialog to a TextBox.Text, which is already bound
我有一个ListBox,它绑定到一个对象列表,在这个ListBox的DataTemplate中,我有一个TextBox,它绑定到这个对象的Property。 现在,我在此DataTemplate中也有一个Button,它会打开一个OpenFileDialog。 我想将此OpenFileDialog的结果绑定到TextBox.Text,所以结果显示在TextBox中,并且绑定到此TextBox的对象的值更改为result。
Xaml:
<ListBox Name="MyList">
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel>
<Button Name="btnOpen" Click="BtnOpen_OnClick"/>
<TextBox Name="txtPath" Text="{Binding Path=Prop2, Mode=TwoWay}"/>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
背后的代码:
private void BtnOpen_OnClick(object sender, RoutedEventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Multiselect = false;
dynamic result = fileDialog.ShowDialog();
if (result == true)
{
//bind to TextBox textproperty here
}
}
绑定到ListBox的列表中的对象的结构如下:
public class Item
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public bool Prop3 { get; set; }
public Item(string prop1)
{
this.Prop1 = prop1;
}
public Item(string prop1, string prop2)
{
this.Prop1 = prop1;
this.Prop2 = prop2;
}
public Item(string prop1, string prop2, bool prop3)
{
this.Prop1 = prop1;
this.Prop2 = prop2;
this.Prop3 = prop3;
}
}
如果Textbox
已绑定到prop1
,则最好更改prop1
值以更改您的文本框文本。 如
private void BtnOpen_OnClick(object sender, RoutedEventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Multiselect = false;
dynamic result = fileDialog.ShowDialog();
if (result == true)
{
prop1=fileDialog.FileName; // set prop1 in the appropriate way.
}
}
因此,文本框文本将被更改。
您的类应实现INofifyPropertyChanged
而集合应实现IListChanged
接口(例如ObservableCollection
或BindingList
如果是这种情况,并且您更新了属性,则绑定控件将更新其内容。
有许多方法可以实现INotifyPropertyChanged。 最快的解决方案是这样的:
public class Item : INotifyPropertyChanged
{
private string prop2;
public string Prop2
{
get { return prop2; }
set { prop2 = value; OnPropertyChanged("Prop2"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var eh = this.PropertyChanged;
if (eh != null)
eh(this, new PropertyChangedEventArgs(propertyName));
}
}
您可以使用基本功能来设置属性值:
if (result == true)
{
txtName.SetValue(TextBox.TextProperty, fileDialog.FileName);
}
我可能宣誓txtPath.Text = fileDialog.FileName;
会为您执行此操作,但是我现在没有编译器对其进行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.