10

WP7 アプリで Web サービスから取得した静的テキストを使用したいと考えています。各テキストには Name (識別子) と Content プロパティがあります。

たとえば、テキストは次のようになります。

Name = "M43";
Content = "This is the text to be shown";

次に、テキストの名前 (つまり、識別子) を に渡したいと思いIValueConverterます。これにより、名前が検索され、テキストが返されます。

コンバーターは次のようになると考えました。

public class StaticTextConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null)
        {
            return App.StaticTexts.Items.SingleOrDefault(t => t.Name.Equals(value)).Content;
        }

        return null;
    }
}

次に、XAML で:

<phone:PhoneApplicationPage.Resources>
    <Helpers:StaticTextConverter x:Name="StaticTextConverter" />
</phone:PhoneApplicationPage.Resources>

...

<TextBlock Text="{Binding 'M43', Converter={StaticResource StaticTextConverter}}"/>

ただし、これは機能していないようで、値をコンバーターに正しく渡すかどうかはわかりません。

誰か提案はありますか?

4

4 に答える 4

14

私はついに答えを見つけました。答えは、@Shawn Kendrot の答えと、私がここで尋ねた別の質問との組み合わせでした

を使用するためのソリューションを要約するIValueConverterには、次の方法でコントロールをバインドする必要があります。

<phone:PhoneApplicationPage.Resources>
    <Helpers:StaticTextConverter x:Name="TextConverter" />
</phone:PhoneApplicationPage.Resources>

<TextBlock Text="{Binding Converter={StaticResource TextConverter}, ConverterParameter=M62}" />

テキストの ID はコンバーター パラメーターで渡されるため、コンバーターはほとんど同じように見えます。

public class StaticTextConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (parameter != null && parameter is string)
        {
            return App.StaticTexts.Items.SingleOrDefault(t => t.Name.Equals(parameter)).Content;
        }

        return null;
    }
}

ただし、結局のところ、バインディング、つまりコンバーターDataContext. これを解決するにDataContextは、コントロールのプロパティを任意の値に設定するだけです:

<TextBlock DataContext="arbitrary" 
           Text="{Binding Converter={StaticResource TextConverter}, ConverterParameter=M62}" />

そして、すべてが意図したとおりに機能します!

于 2012-08-08T07:19:06.863 に答える
8

問題はバインディングにあります。をチェックし、このオブジェクトで、そのオブジェクトのプロパティをDataContext評価しようとします。M62ValueboxConsent

バインドできるアプリケーションのどこかに静的キーを追加したい場合があります。

<TextBlock Text="{Binding Source="{x:Static M62.ValueboxConsent}", Converter={StaticResource StaticTextConverter}}" />

M62 は、キーが配置されている静的クラスです..次のように:

public static class M62
{
    public static string ValueboxConsent
    {
        get { return "myValueBoxConsentKey"; }
    }
}
于 2012-08-03T13:51:48.803 に答える
4

値コンバーターを使用する場合は、値コンバーターのパラメーターに文字列を渡す必要があります

Xaml:

<TextBlock Text="{Binding Converter={StaticResource StaticTextConverter}, ConverterParameter=M43}"/>

コンバータ:

public class StaticTextConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (parameter != null)
        {
            return App.StaticTexts.Items.SingleOrDefault(t => t.Name.Equals(parameter)).Content;
        }

        return null;
    }
}
于 2012-08-03T22:05:03.200 に答える