Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

396
Visualizações
Vincular una propiedad que está fuera de un Itemscontrol en XAML

Estoy tratando de vincular una propiedad que está fuera de un control de elementos. Sin embargo, eso no parece funcionar.

Parece que en ItemsControl, DataTemplate se refiere a lo que está dentro de la colección y no fuera de ella. Probé con RelativeResource y Referido a AncestorType para ViewModel.

Código (MV):

 public class Test { public string GetThis {get{return "123";} set{}} public List<string> IterateProperty {get; set;} }

XAML (Ver):

 <ItemsControl ItemsSource="{Binding Path=IterateProperty}"> <ItemsControl.ItemTemplate> <DataTemplate> <TextBlock Text="I want to bind the string property GetThis!" />
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Debe vincularse al DataContext del ItemsControl principal.

 <ItemsControl ItemsSource="{Binding Path=IterateProperty}"> <ItemsControl.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding DataContext.GetThis, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemsControl}}}" />
over 4 years ago · Santiago Trujillo Relatório

0

He hecho un ejemplo rápido y completo sobre esto:

 <Window x:Class="ParentDataContext.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <DataGrid ItemsSource="{Binding items}" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTemplateColumn> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <CheckBox IsChecked="{Binding IsChecked}"></CheckBox> <TextBlock Margin="5" Text="{Binding Path=DataContext.TextFromParent,RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> </Grid>

El contexto de cada fila se establece para cada objeto de la lista enlazada. En nuestro caso, a cada instancia de Model de la colección de elementos.

Para volver al DataContext del padre, se usa esta sintaxis:

 Text="{Binding Path=DataContext.TextFromParent,RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>

Aquí está el código subyacente:

 public partial class MainWindow : Window { public string TextFromParent { get { return (string)GetValue(TextFromParentProperty); } set { SetValue(TextFromParentProperty, value); } } // Using a DependencyProperty as the backing store for TextFromParent. This enables animation, styling, binding, etc... public static readonly DependencyProperty TextFromParentProperty = DependencyProperty.Register("TextFromParent", typeof(string), typeof(MainWindow), new PropertyMetadata(string.Empty)); public ObservableCollection<Model> items { get; set; } public MainWindow() { InitializeComponent(); items = new ObservableCollection<Model>(); items.Add(new Model() { IsChecked = true }); items.Add(new Model() { IsChecked = false }); items.Add(new Model() { IsChecked = true }); items.Add(new Model() { IsChecked = false }); TextFromParent = "test"; this.DataContext = this; } }

Puede definir su propiedad de dependencia en su ViewModel.

Y aquí está mi modelo simple:

 public class Model : INotifyPropertyChanged { private bool _IsChecked; public bool IsChecked { get { return _IsChecked; } set { _IsChecked = value; PropertyChanged(this, new PropertyChangedEventArgs("IsChecked")); } } public event PropertyChangedEventHandler PropertyChanged = delegate { }; }

Como resultado, puede acceder a la propiedad definida en el DataContext de sus padres.

ingrese la descripción de la imagen aquí

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda