У меня есть следующие ресурсы:ресурсов Стиль не работает в DataTemplate
<UserControl.Resources>
<Style TargetType="{x:Type TextBox}" >
<Setter Property="Background" Value="#FFFFBF" />
<Setter Property="IsEnabled" Value="{Binding Path=EntryEnabled, Mode=TwoWay}" />
</Style>
<DataTemplate x:Key="CommodityTemplate">
<Grid Width="218" HorizontalAlignment="Right">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="30"/>
</Grid.ColumnDefinitions>
<Border Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="4" BorderBrush="Black" BorderThickness="0,0,0,.5" Background="LightCyan" />
<TextBlock Grid.Column="0" Text="{Binding Path=Item_Name}" HorizontalAlignment="Stretch" VerticalAlignment="Center" FontSize="14" />
<StackPanel Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Center" Orientation="Vertical" Margin="2,0" >
<TextBlock Text="{Binding Path=Size}" HorizontalAlignment="Right" FontSize="8" />
<TextBlock Text="{Binding Path=Unit}" HorizontalAlignment="Right" FontSize="8" />
</StackPanel>
<TextBox Grid.Column="2" Text="{Binding Path=Qty_Order, Mode=TwoWay}" FontSize="12" Margin="2,1" />
<TextBox Grid.Column="3" Text="{Binding Path=Qty_Filled, Mode=TwoWay}" FontSize="12" Margin="2,1" IsEnabled="{Binding Path=EntryEnabled, Mode=TwoWay}" />
</Grid>
</DataTemplate>
<DataTemplate x:Key="CategoryTemplate">
<Grid Width="225">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="30"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Border Grid.Row="0" Grid.Column="0" Grid.RowSpan="2" Grid.ColumnSpan="3" BorderBrush="Black" BorderThickness=".5" Background="AliceBlue"/>
<Border Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" BorderBrush="Black" BorderThickness="0,0,0,.5" />
<Border Grid.Row="0" Grid.Column="1" BorderBrush="Black" BorderThickness=".5,0" />
<TextBlock Grid.Column="0" Text="{Binding Path=Category.Description}" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="14" FontWeight="Bold" TextWrapping="Wrap" Margin="5,0"/>
<TextBlock Grid.Column="1" Text="Quantity Ordered" FontSize="7" TextWrapping="Wrap" HorizontalAlignment="Center" VerticalAlignment="Center" >
<TextBlock.LayoutTransform>
<RotateTransform Angle="-90"/>
</TextBlock.LayoutTransform>
</TextBlock>
<TextBlock Grid.Column="2" Text="Quantity filled" FontSize="7" TextWrapping="Wrap" HorizontalAlignment="Center" VerticalAlignment="Center" >
<TextBlock.LayoutTransform>
<RotateTransform Angle="-90"/>
</TextBlock.LayoutTransform>
</TextBlock>
<ListView Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" ItemsSource="{Binding Path=Items, Mode=TwoWay}" ItemTemplate="{StaticResource CommodityTemplate}" />
</Grid>
</DataTemplate>
</UserControl.Resources>
В моем контроле, у меня есть множество элементов управления TextBox.
У меня есть следующий элемент управления LiewView, который использует CategoryTemplate. Этот шаблон содержит еще один элемент управления ListView, который использует CommodityTemplate.
<ListView Grid.Row="1" Grid.Column="1" ItemsSource="{Binding Path=Category_List}" ItemTemplate="{StaticResource CategoryTemplate}"
ScrollViewer.VerticalScrollBarVisibility="Disabled" Background="LightGray" >
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
У меня также есть контроль CheckBox, который, если установлен, я хочу, чтобы все элементы управления TextBox быть отключены.
<CheckBox Grid.Row="3" Grid.Column="1" Content="Has Been Picked-Up" FlowDirection="RightToLeft" IsChecked="{Binding Path=Received, Mode=TwoWay}"
HorizontalAlignment="Right" VerticalAlignment="Center" Margin="20,0" Padding="5,0" IsEnabled="{Binding Path=CBrec_Enabled, Mode=TwoWay}" />
Свойства Received и EntryEnabled находятся в моей модели ViewModel.
#region Received
/// <summary>ViewModel property: Received of type: Boolean points to OrderForm.Received</summary>
public Boolean Received
{
get
{
if (OrderForm == null) return false;
return OrderForm.Received;
}
set
{
if (OrderForm == null) return;
OrderForm.Received = value;
OnPropertyChanged("Received");
OnPropertyChanged("EntryEnabled");
}
}
#endregion
#region EntryEnabled
/// <summary>Property EntryEnabled of type Boolean</summary>
public Boolean EntryEnabled
{
get
{
if (OrderForm == null) return false;
return OrderForm.Received == false;
}
set
{
OnPropertyChanged("EntryEnabled");
}
}
#endregion
Когда я проверяю CheckBox, все элементы управления TextBox отключить, как и ожидалось, для управления TextBox, найденными в CommodityTemplate кроме. Может кто-то сказать мне, что я делаю неправильно. Буду весьма признателен за это.
Это будет связываться с 'EntryEnabled' на текстовое поле в' DataContext', который будет 'DataTemplate '' 'DataContext' - экземпляр класса, отображаемый' DataTemplate'. Какой класс отображается в «CommodityTemplate»? Имеет ли свойство 'EntryEnabled'? Я не видел никаких элементов управления TextBox в любом другом * шаблоне * здесь. Я предполагаю, что 'EntryEnabled' является свойством viewModel' UserControl', а не товарного класса. Решение, вероятно, «Value =» {Binding DataContext.EntryEnabled, RelativeSource = {RelativeSource AncestorType = UserControl}} ". –
Бонус: Быстрый и простой способ узнать, было ли переплетение неправильным: '' {Binding EntryEnabled, PresentationTraceSources.TraceLevel = High} "', а затем смотреть панель вывода в VS во время выполнения. Он расскажет вам все, что он делает, чтобы решить эту проблему, и где она терпит неудачу. Поскольку Bindings имеют такую минимальную поддержку времени разработки или проверку времени компиляции, это чрезвычайно полезно. –
Вот и все! Большое спасибо. – Rod