【问题标题】:WP8 App without Bindings at all?WP8 应用程序根本没有绑定?
【发布时间】:2013-08-11 14:41:31
【问题描述】:

我即将开始为 Windows Phone 8 开发应用程序并开始第一步(我已经有一些使用 WinForms 的 C# 背景)。但我意识到一切,尤其是 XAML,似乎都如此复杂。 * 做最简单的事情(比如填充列表)是一件非常痛苦的事情。它确实适用于扁平且极其简单的绑定(如大多数教程中所建议的那样),但这只是僵硬和不灵活。

我想生成一个包含这些信息的项目列表(LongListSelector)(“o”是每个项目):

<o.Name>
<o.TotalAmount> (<o.Things.Count>)
[if o.MiscThings.Count > 0]<o.MiscThings.Count> other thing(s)[/if]

数据示例:

John Doe
22.97 (3)
2 other thing(s)

Jane Doe
7.55 (1)

我试图通过以下方式实现:

<phone:LongListSelector x:Name="LLS_Summary">
    <phone:LongListSelector.ItemTemplate>
        <DataTemplate>
            <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top">
                <TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextLargeStyle}" />
                <TextBlock Text="{Binding TotalAmount} ({Binding Things.Count})" /> <!-- throws an error, concatenation doesn't work? -->
                <!-- well yeah this is obviously not possible with data binding -->
            </StackPanel>
        </DataTemplate>
    </phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>

// in .cs
LLS_Summary.ItemsSource = App.MyItems; // IList

甚至没有接近。仅当我事先有某种转换器并且有条件的东西根本无法以这种方式工作时,连接似乎才起作用。

所以我的方法是自己在运行时生成元素。但是怎么做? LongListSelector 控件似乎根本不支持这一点。在 WinForms 中,我会执行以下操作:

Label line1 = new Label();
line1.Text = o.Name;
Label line2 = new Label();
line2.Text = o.TotalAmount + " (" + o.Things.Count + ")";
Label line3 = new Label();
if (o.MiscThings.Count > 0)
    line3.Text = o.MiscThings.Count + " other thing(s)";
else
    line3.Text = "";

// sizing, positioning etc.

Panel panel = new Panel();
panel.Controls.Add(line1);
panel.Controls.Add(line2);
panel.Controls.Add(line3);

LLS_Summary.Controls.Add(panel);

如何在 Win(P)RT 中实现这一点?这甚至是这样做的方法吗?

【问题讨论】:

    标签: xaml windows-phone-8 windows-runtime winrt-xaml


    【解决方案1】:

    一个属性只能有一个绑定,实现类似

    <TextBlock Text="{Binding TotalAmount} ({Binding Things.Count})" />
    

    您可以使用两个文本块,也可以使用 Runs 和 StringFormat

    <TextBlock>
         <Run Text="{Binding TotalAmount}"/>
         <Run Text="{Binding Things.Count, StringFormat='{}({0})'}"/>
    </TextBlock>
    

    【讨论】:

    • 谢谢,但是条件文本块呢?
    • 那时我会首先研究诸如值转换器之类的东西,或者如果更改与数据模板选择器有很大不同。
    • 值转换器绝对是前进的方向,并且是 xaml 数据绑定的内在部分。它们有助于将您的逻辑与表示层分开。
    猜你喜欢
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    相关资源
    最近更新 更多