我在 WPF 中得到了以下 xaml 绑定(bind)场景。在 Grid
的资源中定义 UIElements
。将这些静态资源绑定(bind)到 ToggleButton
的 Tag
属性。单击切换按钮,将 Tag
属性分配给 ContentControl
的 Content
属性。
<Grid>
<Grid.Resources>
<TextBlock x:Key="t1"
Grid.Row="1"
Text="Text1" />
<TextBlock x:Key="t2"
Grid.Row="1"
Text="Text2" />
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal"
HorizontalAlignment="Center">
<ToggleButton Tag="{StaticResource t1}"
Margin="10"
Click="ButtonBase_OnClick"
Content="T1" />
<ToggleButton Tag="{StaticResource t2}"
Margin="10"
Click="ButtonBase_OnClick"
Content="T1" />
</StackPanel>
<ContentControl x:Name="cc"
Grid.Row="1" />
</Grid>
单击切换按钮只会将标记值分配给 Content
属性。
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
cc.Content = ((FrameworkElement)sender).Tag;
}
虽然这在全能的 WPF 中有效,但在 WinRT 中则不可能。 WinRT 提示 ArgumentException
“值不在预期范围内。”。我不知道为什么?
出于测试目的,我尝试在事件处理程序中直接分配,其按预期工作:
cc.Content = new TextBlock { Text = "Text1" };
为了让它变得更奇怪,我在 WinRT 中尝试了这个:
<ContentControl x:Name="cc"
Content="{StaticResource t1}"
Grid.Row="1" />
结果:它在设计器中有效,但在运行时失败。对此更是一无所知。
首先,ArgumentException 试图告诉我什么?其次为什么它在 WPF 中工作?运行时和 VS 设计器之间的差异怎么样?
最佳答案
在 Win RT/Windows 8 应用商店应用程序中,内容控件不能包含已存在于其他位置的 View 中的元素。由于它存在于 Grid.Resources 中,因此无法将其添加到 ContentControl。
我建议在资源中制作一个 DataTemplate:
<Grid>
<Grid.Resources>
<DataTemplate x:Key="t1">
<TextBlock Text="Text1" />
</DataTemplate>
...
然后在按钮中单击类似以下内容的内容:
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var dataTemplate = ((FrameworkElement)sender).Tag as DataTemplate;
cc.Content = dataTemplate.LoadContent() as FrameworkElement;
}
注意:我没有机会对此进行测试。
关于wpf - 从代码隐藏设置 ContentControls 内容属性会引发异常 'value does not fall in range',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17095254/