【问题标题】:How to uniquely position usercontrols from an ItemsControl (in MVVM)?如何从 ItemsControl(在 MVVM 中)中唯一地定位用户控件?
【发布时间】:2015-01-05 05:55:21
【问题描述】:

我正在尝试从 ItemsControl 中呈现用户控件 CharacterEditorView。 (ItemsPanelTemplate中“Canvas”的使用可以改变,Grid?)。 CharacterEditorView 是覆盖在字符串之上的,所以位置很关键。 ItemsControl 是:

    <ItemsControl Grid.Row="0" Grid.RowSpan="1" ItemsSource="{Binding CharacterPads}" >
                   <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <Canvas />
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.ItemContainerStyle>
                        <Style>
                            <Setter Property="Control.Margin" Value="{Binding Margin}"/>
                        </Style>
                    </ItemsControl.ItemContainerStyle>
                </ItemsControl>

其中 CharacterPads 的绑定定义为:

   private ObservableCollection<CharacterEditorViewModel> characterPads = new ObservableCollection<CharacterEditorViewModel>();
    public ObservableCollection<CharacterEditorViewModel> CharacterPads
    {
        get
        {
            return characterPads;
        }
    }

我想在一个特定的矩形内呈现每个 CharacterEditorView,该矩形仅在其视图模型创建时才知道。也就是说,每个 CharacterEditorView 都会有不同的 要呈现的矩形:

<UserControl x:Class="Nova5.UI.Views.CharacterEditorView"
       .................................................................
     <Grid Background="Red">
        <TextBlock Text="TextBlock" Margin="{Binding ...?????}" />
     </Grid>
</UserControl>

需要什么绑定才能将每个 CharacterEditorView 定位到自己的位置?

感谢您的任何想法。

【问题讨论】:

标签: wpf xaml mvvm


【解决方案1】:

如果您想绑定 TextBlock 的 Margin,您需要在 CharacterEditorViewModel 中提供一些 Thickness 类型的可绑定属性并将其指定为绑定目标(或者,为了更简洁的代码,请在 ViewModel 中提供数字属性和实现一个 ValueConverter,从它们中创建一个 Thickness 实例)。

或者,由于 ItemsPanelTemplate 已定义为 Canvas,因此按照 HighCore 的建议,将这些数字属性直接绑定到 Canvas.Left 和 Canvas.Top。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 2017-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多