Binding between Resources.DataTemplate and ListBox.DataTemplate - Windows Phone

喜夏-厌秋 提交于 2019-12-13 05:08:40

问题


I'm having problems to do a binding in Windows Phone. Hope you can help me.

I have the following Data Template in App.xaml:

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

I have a ListBox with the following Data Template:

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

The ListBox receives the following Class in the ItemsSource Property:

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; }
   }

}

Is there anyway to bind the Resources.TextBox.Text property with the Object of the ListBoxItem like...

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


回答1:


In the end, I couldn't Bind the properties thru xaml, but I did it thru code.

I have the DataTemplate in a CustomMessageBox. So, I got the Textbox inside the CustomMessageBox with a method which I created:

    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;

    }

So, I just called the method and assigned the value that I wanted:

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



回答2:


You cannot use ElementName binding when the item is not in the same NameScope.
The easiest way to do what you want is probably to bind SelectedItem to a property in your viewmodel and use this property to bind the Text of your TextBox.



来源:https://stackoverflow.com/questions/18838053/binding-between-resources-datatemplate-and-listbox-datatemplate-windows-phone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!