问题
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