【问题标题】:wpf bind textbox to List - MainWindow.List.Item[0]wpf 将文本框绑定到列表 - MainWindow.List.Item[0]
【发布时间】:2015-12-03 17:52:20
【问题描述】:

我的主窗口中有一个静态列表。如果发生更改,则立即设置 CurrValue。

public static List<varVisu> varVisuListDll = new List<varVisu>();

在我的课堂上,有一个 INotifyPropertyChanged 实现

    public string m_CurrValue;

    public event PropertyChangedEventHandler PropertyChanged;
    protected void Notify(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public string CurrValue
    {
        get { return m_CurrValue; }
        set 
        {
            if (value != m_CurrValue)
            {
                //set value
                m_CurrValue = value;
                //notify anyone who cares about it
                Notify("CurrValue");
            }
        }
    }

这工作正常,但现在,我想将 Window#2 中的文本框(文本)绑定到此列表中的第一项 (varVisuListDll[0].CurrValue)

如何将 TextBox.Text 绑定到该值(Text={Path, UpdateSourceTrigger ...}??

<TextBox x:Name="txtManualMode" Text="{Binding ElementName=????, Path=CurrValue, UpdateSourceTrigger=PropertyChanged}" 

我已经使用 (dtgrVariables.ItemSource=MainWindow.varVisuListDll) 进行了测试。这部作品。

请帮帮我..

【问题讨论】:

    标签: c# wpf user-interface textbox updatesourcetrigger


    【解决方案1】:

    我已经解决了这个问题。

    我在后面的代码中设置了绑定。这工作很好。

            varVisu v1 = MainWindow.varVisuListDll[1];
            txtManualMode.DataContext = v1;
            Binding binding = new Binding() { Path = new PropertyPath("CurrValue") };
            txtManualMode.SetBinding(TextBox.TextProperty, binding);
    

    【讨论】:

    • 如果您也可以在 XAML 中编写一个简单的绑定表达式,并让 varVisuListDll 成为公共属性而不是字段,那是没有意义的。我的回答有没有你不明白的地方?
    • 我明白了。但就我而言(在下一步中),我必须将变量(x)设置为控件(x)。通过绑定代码,我可以将变量动态映射到控件。
    【解决方案2】:

    varVisuListDll 必须是属性,而不是字段:

    private static List<varVisu> varVisuListDll = new List<varVisu>();
    
    public static List<varVisu> VarVisuListDll
    {
        get { return varVisuListDll; }
    }
    

    那么绑定应该是这样的:

    <TextBox Text="{Binding Path=(local:MainWindow.VarVisuListDll)[0].CurrValue}"/>
    

    或者,如果您使用的是比 .NET 4 更旧的框架:

    <TextBox Text="{Binding Path=[0].CurrValue,
                            Source={x:Static local:MainWindow.VarVisuListDll}}"/>
    

    【讨论】:

      猜你喜欢
      • 2012-05-09
      • 2011-08-28
      • 2011-10-13
      • 2011-05-07
      • 1970-01-01
      • 2011-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多