【问题标题】:Silverlight set property path in converter?Silverlight 在转换器中设置属性路径?
【发布时间】:2012-03-22 08:14:38
【问题描述】:

我有一个列表框,它有多个用于其项目的数据模板。使用转换器选择数据模板并解释 ListBox 的对象集合。

在转换器内部,我试图将 datacontext(lisbox 外部)的属性绑定到数据模板的 TextBox 控件。

列表框:

<telerik:RadListBox
            x:Name="listBox2"
            ItemsSource="{Binding MyCollection, Mode=TwoWay}"
            VerticalAlignment="Top" Height="400">

            <telerik:RadListBox.ItemTemplate>
                <DataTemplate>
                    <ContentControl Content="{Binding}"
                                    ContentTemplate="{Binding Converter={StaticResource myTestConverter}, ConverterParameter={StaticResource myViewModel}}" />
                </DataTemplate>
            </telerik:RadListBox.ItemTemplate>
        </telerik:RadListBox>

数据模板:

<DataTemplate x:Key="TestResource1">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding propertyLabel}"
                       FontStyle="Italic" Width="120" />
            <TextBox x:Name="valueField"  
                       FontSize="12" Width="50"
                       FontWeight="Bold" />
        </StackPanel>
    </DataTemplate>

Converter的convert方法内部:

_dt = Application.Current.Resources["TestResource1"] as DataTemplate;
                var context = _dt.LoadContent();

                var ctrl = FindControlByType<TextBox>(context, "valueField");

                Binding binding = new Binding("DataContext.Value1");
                binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor) { AncestorType = typeof(MainPage) };

                TextBox txtBox = ctrl as TextBox;
                BindingOperations.SetBinding(txtBox, TextBox.TextProperty, binding);

这不起作用。知道我做错了什么吗?

谢谢。

【问题讨论】:

    标签: silverlight xaml mvvm silverlight-5.0


    【解决方案1】:

    LoadContent 不适合您的原因是,这通常由控件本身在 OnApplyTemplate() 期间调用。

    在这种情况下,我发现使用XamlReader.Load() 加载一个自定义的DataTemplate 然后将其分配给控件更容易。

    【讨论】:

    • 嗨,_dt.LoadContent() 工作正常,我的问题是“DataContext.Value1”的绑定没有被拾取。我将尝试您动态创建数据模板的建议。也许这会奏效。感谢您的回复。
    • Silverlight 调用 LoadContent() 并将返回值放置在可视化树中。当你调用 LoadContent 时,除非你把它放在可视化树中,否则你不会看到任何结果。
    • 我认为我们在这里有所作为。我的绑定中有一个相对源,如下所示: string str = @"schemas.microsoft.com/client/2007"" xmlns:local=""clr-namespace:MyListBoxProject"">TextBlock Text=" "{Binding propertyLabel}"" />";但我收到此错误消息:无法从文本“local:MainPage”创建“System.Type”。如果我绑定到普通属性,它可以正常工作。
    • 关于您对 LoadContent 的评论,我尝试在绑定后再次调用 LoadContent,但结果没有改变。你有那个例子吗?
    • 很遗憾,LoadContent 只对控件作者有用。 LoadContent 每次都会创建新控件,它永远不会返回由屏幕上的实际模板创建的控件。要获得这些,您必须遍历可视化树。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 2018-03-21
    相关资源
    最近更新 更多