您好我是 XAML 的新手,我正在尝试构建一个自定义切换按钮控件。我的控件有以下代码,它没有给出任何编译或运行时错误,但不显示数据。当我尝试进行常规模板绑定时,我不断收到错误,经过研究我发现我需要使用相对源。但无法让列表填充。有人可以指导我做错了什么吗?或者如果有更好的方法来做到这一点?
目标:构建一个具有列表控件的可检查控件。
XAML Generic.xml:(此代码位于切换按钮控件模板中)
<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>