在自定义按钮控件中绑定ListBox或ItemsControl

时间:2012-12-07 17:14:41

标签: listbox controls relativesource templatebinding

您好我是XAML的新手,我正在尝试构建自定义切换按钮控件。我的控件具有以下代码,它不会产生任何编译或运行时错误但不显示数据。当我尝试进行常规模板绑定时,我不断收到错误,经过研究后发现我需要使用相对源。但是无法填写清单。有人可以指导我做错了吗?或者,如果有更好的方法来做到这一点?

目标:构建一个具有列表控件的可检查控件。

XAML Generic.xml:(此代码位于togglebutton controltemplate中)

    <ListBox BorderBrush="Red" BorderThickness="2" 
ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=MyRoutes}">
<!--<ItemsControl.ItemsSource>
<Binding Mode="TwoWay" Path="MyRoutes">
<Binding.RelativeSource>
<RelativeSource Mode="TemplatedParent"/>
</Binding.RelativeSource>
</Binding>
</ItemsControl.ItemsSource>-->
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<!--<TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Value}"></TextBlock>-->
<TextBlock Text="{Binding Path=Value, RelativeSource={RelativeSource Self}}"></TextBlock>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>

在PlainToggleButton.cs后面的代码:

public string[] MyRoutes
    {
        get { return (string[])GetValue(MyRoutesProperty); }
        set { SetValue(MyRoutesProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MyRoutes.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MyRoutesProperty =
        DependencyProperty.Register("MyRoutes", typeof(string[]), typeof(PlainToggleButton), new PropertyMetadata(OnMyRoutesChanged));

    private static void OnMyRoutesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        return;
    }

代码MainWindow.xaml:

<local:PlainToggleButton Grid.Row="1" MyRoutes="{Binding MyRoutes}">            
    </local:PlainToggleButton>

0 个答案:

没有答案