如何以编程方式将自定义布局网格位置设置为 StatusBarItem?

How to set custom layout grid position to StatusBarItem programmatically?

我想要在我的项目中有一个动态状态栏

所以我将 ItemSource 设置为 Binding

<StatusBar ItemsSource="{Binding StatusBarItemsSource}" DockPanel.Dock="Bottom" >

并在我的主视图模型中创建了一个 BindingList

public static BindingList<StatusBarItem> StatusBarItemsSource { get; set; }

在初始化时我在右下角添加了我的标志

StatusBarItem logo = new StatusBarItem
{
    HorizontalAlignment = HorizontalAlignment.Right,
    Content = new Image
    {
        Source = new BitmapImage(new Uri("Logo.ico", UriKind.Relative)),
        Width = 16,
        Height = 16
    }
};
StatusBarItemsSource.Add(logo); 

到目前为止一切顺利,徽标出现在右下角

但是

如果我想在另一个视图中添加另一个 StatusBarItem 以显示左侧视图的总和文本,徽标也会显示在左侧

主视图模型:

public static void AddItemToStatusBar(Object content, HorizontalAlignment alignment = HorizontalAlignment.Stretch)
{
    StatusBarItem statusBarItem = new StatusBarItem
    {
        HorizontalAlignment = alignment,
        Content = content
    };
    StatusBarItemsSource.Add(statusBarItem);
}

另一个视图模型:

TextBlock someTextBlock = new TextBlock { Text = someString };
MainViewModel.AddItemToStatusBar(someTextBlock , System.Windows.HorizontalAlignment.Left);

然后我在 Whosebug 上找到了将网格设置为模板的可能性 How do I customize the WPF StatusBar layout?

所以我将此添加到我的代码中:

<StatusBar ItemsSource="{Binding StatusBarItemsSource}" DockPanel.Dock="Bottom" >
    <StatusBar.ItemsPanel>
        <ItemsPanelTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="100" />
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="100" />
                </Grid.ColumnDefinitions>
            </Grid>
        </ItemsPanelTemplate>
    </StatusBar.ItemsPanel>
</StatusBar>

如何定义XAML中的列很清楚

<StatusBarItem Grid.Column="3">
    <TextBlock>some String</TextBlock>
</StatusBarItem>

但是如何在我的视图模型中执行此操作?

我试过 statusBarItem.Grid.Column = 3 / "3"statusBarItem.Grid.SetColumn 但没有成功

我希望你能帮助我,这个小问题没有太大的影响

Grid.SetColumn还不错,但我用错了

现在是这样的:

StatusBarItem logo = new StatusBarItem
{
    Content = new Image
    {
        Source = new BitmapImage(new Uri("logo.ico", UriKind.Relative)),
        Width = 16,
        Height = 16
    }
};
Grid.SetColumn(logo, 2);
StatusBarItemsSource.Add(logo);