【问题标题】:Binding between Resources.DataTemplate and ListBox.DataTemplate - Windows PhoneResources.DataTemplate 和 ListBox.DataTemplate 之间的绑定 - Windows Phone
【发布时间】:2013-09-16 22:02:28
【问题描述】:

我在 Windows Phone 中进行绑定时遇到问题。希望你能帮助我。

我在 App.xaml 中有以下数据模板:

<Application.Resources>
<DataTemplate>
<TextBox Name="txt1"/>
<TextBox Name="txt2"/>
</DataTemplate>
</Application.Resources>

我有一个带有以下数据模板的列表框:

<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Name="txt1"/>
<TextBox Name="txt2"/>
</DataTemplate>
<ListBox.ItemTemplate>
<ListBox>

ListBox 在 ItemsSource 属性中接收以下类:

public class Product
{

   private int _id;
   public int Id
   {
       get { return _id; }
       set { _id = value; }
   }

   private string _name;

   public string Name
   {
       get { return _name; }
       set { _name = value; }
   }

}

有没有办法将 Resources.TextBox.Text 属性与 ListBoxItem 的对象绑定,例如...

<Application.Resources>
<TextBox Name="txt1" Text={Binding ElementName=ListBox, Path=SelectedItem.Product.Name}/>
</Application.Resources>

【问题讨论】:

    标签: windows-phone-7 binding windows-phone-8 windows-phone


    【解决方案1】:

    最后,我无法通过 xaml 绑定属性,但我通过代码做到了。

    我在 CustomMessageBox 中有 DataTemplate。因此,我使用我创建的方法在 CustomMessageBox 中获取了文本框:

        public T SearchControl<T>(DependencyObject parent, string nameControl)
            where T : DependencyObject
        {
    
            if (parent == null || string.IsNullOrEmpty(nameControl))
                return null;
    
            if (parent is T && ((FrameworkElement)parent).Name == nameControl)
                return parent as T;
    
            int totalControles = VisualTreeHelper.GetChildrenCount(parent);
    
            for (int i = 0; i < totalControles; i++)
            {
    
                var child = VisualTreeHelper.GetChild(parent, i);
    
                T control = BuscarControl<T>(child, nameControl);
    
                if (control != null)
                    return control;
    
            }
    
            return null;
    
        }
    

    所以,我只是调用了该方法并分配了我想要的值:

    (SearchControl<TextBox>(CustomMessageBox, "txt1")).Text = Value;
    

    【讨论】:

      【解决方案2】:

      当项目不在同一个 NameScope 中时,您不能使用 ElementName 绑定。
      做你想做的最简单的方法可能是将 SelectedItem 绑定到你的视图模型中的一个属性,并使用这个属性来绑定你的 TextBox 的文本。

      【讨论】:

      • 使用 IValueConverter 怎么样?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-15
      • 2013-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-18
      相关资源
      最近更新 更多