I have a problem with localizations and a UserControl in my Windows Phone 8 App on XAML and C#. Unfortunately I didn't find a helpful solution to my problem despite trying to fix it the whole weekend.

The problem:

I have a custom UserControl, which I use in MainPage.xaml. I tried to bind a localized string to the IngredientName, but I get:

System.Windows.Markup.XamlParseException (Failed to assign to property)

This is MyUserControl.xaml:

<UserControl x:Name="myuc">
        <TextBlock x:Name="txt_IngredientName />
</UserControl>

In the code-behind (MyUserControl.xaml.cs) I use the following lines to set and get values in the MainPage:

public string IngredientName
{
    get { return this.txt_ingredientName.Text; }
    set { this.txt_ingredientName.Text = value; }
}

In MainPage.xaml I call the UserControl the following way:

<local:MyUserControl IngredientName="Chocolate"/>

This works fine. But when I want to use a localized string:

IngredientName="{Binding Path=LocalizedResources.Chocolate, Source={StaticResource LocalizedStrings}}"

I get the error.

I read and tried a lot about Dependencies, Bindings, and so on, but I didn't get it work. Does anyone know to use localized strings on a UserControl the proper way? Or can somebody give me a hint?

有帮助吗?

解决方案

For Binding to work you need a DependencyProperty. Place the following code in MyUserControl:

public static readonly DependencyProperty IngredientNameProperty
    = DependencyProperty.Register(
        "IngredientName",
        typeof(string),
        typeof(MyUserControl),
        new PropertyMetadata(HandleIngredientNameChanged));

public string IngredientName
{
    get { return (string)GetValue(IngredientNameProperty); }
    set { SetValue(IngredientNameProperty, value); }
}

private static void HandleIngredientNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var control = (MyUserControl) d;
    control.txt_ingredientName.Text = (string) e.NewValue;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top