В Python переменная, объявленная вне функции или в глобальной области действия, называется глобальной. Это означает, что глобальная переменная может быть доступна внутри или вне функции.
Но мы можем получить доступ только к глобальной переменной, но не можем ее модифицировать внутри функции. Если мы попытаемся сделать это, ошибка покажет
UnboundLocalError: локальная переменная 'c', на которую ссылаются перед присваиванием
blockquote>. Решение для этого - использовать глобальную ключевое слово.
a, b, c = (1, 2, 3) print(a, b, c) def test(): print(a) print(b) print(c) global c # (A) c+=1 # (B) test()
Если вы используете python 3, вы также можете использовать нелокальное ключевое слово
def test(): print(a) print(b) print(c) ninlocal c # (A) c+=1 # (B) test()
Вам нужно привязать к DataContext
родительского ItemsControl
.
<ItemsControl ItemsSource="{Binding Path=IterateProperty}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding DataContext.GetThis,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type ItemsControl}}}" />
Я сделал быстрый и полный пример:
<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>
Контекст каждой строки задан для каждого объекта из связанного списка. В нашем случае для каждого экземпляра модели из коллекции элементов.
Чтобы вернуться к DataContext родительского элемента, этот синтаксис используется:
Text="{Binding Path=DataContext.TextFromParent,RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
Вот код:
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;
}
}
Вы можете определить свое свойство зависимостей в вашей ViewModel.
И вот моя простая модель:
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 { };
}
В результате вы можете получить доступ к свойству, определенному в DataContext вашего родителя.
[/g0]