【发布时间】:2010-04-20 21:52:37
【问题描述】:
从 SL3 升级 -> SL4。第一个问题:这会引发解析器异常:
<StackPanel Name={Binding} /> (same with x:Name)
集合是ObservableCollection<string>。在 SL3 中运行良好。所以似乎 SL4 不允许绑定到 Name 属性。嗯?
所以:改为
<StackPanel Tag={Binding} />
... 因为我只需要在后面的代码中标识控件。所以这是错误('因为这一定是一个错误!):
在这个片段中,AllAvailableItems 是一个ObservableCollection<string>:
<ItemsControl Name="lbItems"
ItemsSource="{Binding AllAvailableItems}"
Height="Auto"
Width="Auto"
BorderBrush="Transparent"
BorderThickness="0"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Margin="12,6,0,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<CheckBox Tag="{Binding}"
Checked="ItemChecked_Click"
Unchecked="ItemUnchecked_Click"
Style="{StaticResource CheckBoxStyle}"
Grid.Row="0">
<CheckBox.Content>
<TextBlock Text="{Binding}"
Style="{StaticResource FormLJustStyle}" />
</CheckBox.Content>
</CheckBox>
<StackPanel Tag="{Binding}"
Orientation="Vertical"
Grid.Row="1">
<configControls:ucLanguage /> <!-- simple user control -->
</StackPanel>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
在后面的代码中,我使用递归函数来查找提供了 Name 或 Tag 属性的 Dependency 对象:
public static T FindVisualChildByName<T>(DependencyObject parent, string name, DependencyProperty propToUse) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
string controlName = child.GetValue(propToUse) as string;
if (controlName == name)
{
return child as T;
}
else
{
T result = FindVisualChildByName<T>(child, name, propToUse);
if (result != null)
return result;
}
}
return null;
}
好的,得到这个:在后面的代码中,我可以得到 XAML 中 ORDERED FIRST 的控件!换句话说,如果我把 CheckBox 放在首位,我可以检索 CheckBox,但没有 StackPanel。反之亦然。这一切在 SL3 中运行良好。
任何帮助,想法...?
谢谢 - 库尔特
【问题讨论】:
-
AllAvailableItems 是您的 DataContext 吗?您提到了它,但我没有在您的代码中看到它。我用硬编码的“标签”测试了你的情况,我可以成功检索 StackPanel,所以它一定是你的绑定有问题。
-
就像我说的,这段代码非常适合 SL3。 AllAvailableItems 属性是我的 ViewModel 的成员,并且在运行时可用 - 正如我所提到的,我可以使用它的值来实例化绑定在我的 ItemsControl 中的 Checkbox 或 StackPanel - 但不能同时实例化,并且只有首先声明的那个在 Xaml 中!
-
您还没有定义什么构成“这在 SL3 中有效”,它在什么方面有效?您描述了只有第一个订购的项目被函数返回的事实,您还期待什么?在我看来,该函数将搜索与您正在寻找的条件相匹配的所需项目并返回。按道理它会返回它遇到的第一个,但你似乎表明这是一个问题,怎么回事?
-
这里有 2 个问题:1) SL4 不允许数据绑定到控件的 Name 或 x:Name 属性。无赖,但哦,好吧。更重要的是,2)绑定在这里无法正常工作,IMO。我可以将集合绑定到 ItemsControl,是吗?我可以将项目属性(单个字符串)分配给 DataTemplate 中控件的标记属性,是吗?我想要多少就多少!但是......我只能使用这个 Tag 属性来使用 VisualTreeHelper 检索模板中的 FIRST DECLARED 控件吗?自己试试——对我来说闻起来像个虫子。希望我错了,我写了一个 hack,但它并不漂亮。