[英]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.