c# - WPF:如何将 OpenFileDialog 的结果绑定(bind)到已绑定(bind)的 TextBox.Text

标签 c# wpf xaml data-binding

我有一个列表框,它绑定(bind)到一个对象列表,在这个列表框的数据模板中,我有一个文本框,它绑定(bind)到该对象的属性。现在,我在此 DataTemplate 中也有一个按钮,用于打开 OpenFileDialog。我想将此 OpenFileDialog 的结果绑定(bind)到 TextBox.Text,以便结果显示在 TextBox 中,并且绑定(bind)到此 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
    }
}

列表中绑定(bind)到 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;
    }
}

最佳答案

您的类应实现 INofifyPropertyChanged 并且您的集合应实现 IListChanged 接口(interface)(例如 ObservableCollectionBindingList

如果是这种情况,并且您更新属性,则绑定(bind)控件将更新其内容。

有很多方法可以实现 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));
    }

}

关于c# - WPF:如何将 OpenFileDialog 的结果绑定(bind)到已绑定(bind)的 TextBox.Text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32306348/

相关文章:

wpf - 过时的 UI 自动化树

c# - 无法从 WPF 中的集合绑定(bind)模型的 DependcyProperty

c# - User32.dll : RegisterHotkey not found

c# - 强制(通用)值类型成为引用

c# - 如何按需运行后台服务 - 而不是在应用程序启动或计时器上

c# - .NET Core - 全局化和本地化 - 类库

c# - 在运行时添加按钮不起作用

c# - 在 silverlight 中添加自定义字体

wpf - 从 UI 绑定(bind)到 View 模型属性需要从 TextBox 中移除焦点

c# - 如何在通用应用程序中使用样式按下时更改文本 block 按钮内容