我将ListBox
Xaml 中的 a 绑定到一个NetworkViewModel
包含实例集合的NodeViewModel
实例。实例应显示NodeViewModel
在画布上的 X 和 Y 位置,由NodeViewModel
.
我想绑定ListBoxItem
的画布。左和帆布。从顶部到 X 和 Y。我假设在 WinUI 中不可能在样式中使用绑定。一种解决方法可能是一个辅助类,它带有绑定源路径的附加属性。PropertyChangedCallback
它在辅助属性的 a 后面的代码中创建绑定。但是绑定不起作用,为什么?
void BindingHelperNodes::OnBindingPathPropertyChanged( winrt::Microsoft::UI::Xaml::DependencyObject const& d,
winrt::Microsoft::UI::Xaml::DependencyPropertyChangedEventArgs const& e )
{
if(Microsoft::UI::Xaml::Controls::ListBoxItem item{ d.try_as<Microsoft::UI::Xaml::Controls::ListBoxItem>() })
{
Microsoft::UI::Xaml::Controls::Canvas::LeftProperty;
Microsoft::UI::Xaml::Data::Binding binding;
binding.Mode( Microsoft::UI::Xaml::Data::BindingMode::OneWay );
Microsoft::UI::Xaml::PropertyPath propertyPath( L"Y" );
binding.Path( propertyPath );
Microsoft::UI::Xaml::Data::RelativeSource relativeSource;
relativeSource.Mode( Microsoft::UI::Xaml::Data::RelativeSourceMode::Self );
binding.RelativeSource( relativeSource );
Microsoft::UI::Xaml::Data::BindingOperations::SetBinding(
d,
Microsoft::UI::Xaml::Controls::Canvas::LeftProperty(),
binding);
//item.SetBinding( Microsoft::UI::Xaml::Controls::Canvas::LeftProperty(), binding );
}
}
<Grid>
<Grid.Resources>
<ResourceDictionary>
<Style x:Name="listBoxItemContainerStyle2" TargetType="ListBoxItem">
<Setter Property="Canvas.Left" Value="0"/>
</Style>
</ResourceDictionary>
</Grid.Resources>
<ListBox Grid.Row="1" ItemsSource="{x:Bind mainViewModel.NetworkViewModel.Nodes, Mode=OneWay}"
>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="local:BindingHelperNodes.CanvasLeftBindingPath" Value="X"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ListBox.Template>
<ControlTemplate TargetType="ListBox">
<ItemsPresenter />
</ControlTemplate>
</ListBox.Template>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Background="Transparent" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate x:DataType="local:NodeViewModel">
<Grid
Width="120"
Height="60"
>
<!-- This rectangle is the main visual for the node. -->
<Rectangle
Stroke="Black"
Fill="White"
RadiusX="40"
RadiusY="40"
/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>