【发布时间】:2015-11-25 04:46:23
【问题描述】:
我有一个 ListBox,它绑定到一个对象列表,在这个 ListBox 的 DataTemplate 中我有一个 TextBox,它绑定到这个对象的一个属性。现在我在这个 DataTemplate 中也有一个按钮,它打开了一个 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;
}
}
【问题讨论】:
-
你试过
txtPath.Text = fileDialog.FileName;吗? -
是的,但是如果我这样做了,我会覆盖绑定并且不会更改值 Prop2
标签: c# wpf xaml data-binding