wpf 列表框数据绑定

发布于 2024-09-25 12:35:40 字数 894 浏览 4 评论 0原文

我有一个列表框,它从字典大小中获取值:

这是大小类型:

public Dictionary<string, int> Size
    {
        get;
        private set;
    }

这是我的列表框

<ListBox x:Name="boardSize" ItemsSource="{Binding Size}" ItemTemplate="{DynamicResource DataTemplate1}" />

这是我关联的数据模板:

<Rectangle Margin="8,8,16,8" Stroke="Black" RadiusX="45" RadiusY="45">
 <Rectangle.Fill>
  <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
   <GradientStop Color="Black" Offset="0"/>
   <GradientStop Color="#FFE24A4A" Offset="1"/>
  </LinearGradientBrush>
 </Rectangle.Fill>
</Rectangle>
<TextBlock x:Name="textBlock" **Text="{Binding path=Size}"**/>

我有两个问题:

  1. 我在哪里放置 ** 我希望文本块文本包含 Size 键值,
  2. 按下按钮时如何执行命令模式?

i have a listbox who takes values from Dictionary Size:

this is the Size type:

public Dictionary<string, int> Size
    {
        get;
        private set;
    }

this is my listbox

<ListBox x:Name="boardSize" ItemsSource="{Binding Size}" ItemTemplate="{DynamicResource DataTemplate1}" />

this is my the associated DataTemplate:

<Rectangle Margin="8,8,16,8" Stroke="Black" RadiusX="45" RadiusY="45">
 <Rectangle.Fill>
  <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
   <GradientStop Color="Black" Offset="0"/>
   <GradientStop Color="#FFE24A4A" Offset="1"/>
  </LinearGradientBrush>
 </Rectangle.Fill>
</Rectangle>
<TextBlock x:Name="textBlock" **Text="{Binding path=Size}"**/>

I have two problems:

  1. where I putted ** I want the textblock text to contain the Size key value
  2. how can I do command pattern when a button is pushed ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

奈何桥上唱咆哮 2024-10-02 12:35:40

ItemTemplate 内,DataContext 是源集合中的一项,因此在这种情况下它是一个 KeyValuePair。所以密钥的路径就是“Key”:

<TextBlock x:Name="textBlock" Text="{Binding path=Key}"/>

你的第二个问题不是很清楚,你到底想做什么?通常,在 MVVM 中使用绑定到命令:绑定到 ViewModel 公开的 ICommand 属性。但是,在您的情况下,没有 ViewModel,因为您的数据对象是 KeyValuePair...如果您想要更完整的答案,请提供更多详细信息

Inside the ItemTemplate, the DataContext is an item from the source collection, so in that case it's a KeyValuePair<string, int>. So the path to the key is just "Key" :

<TextBlock x:Name="textBlock" Text="{Binding path=Key}"/>

Your second question is not very clear, what do you want to do exactly ? Usually, binding to commands is used in MVVM: you bind to a ICommand property exposed by your ViewModel. However in your case there is not ViewModel, since your data object is a KeyValuePair<string, int>... Please give more details if you want a more complete answer

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文