lebhero
lebhero

Reputation: 1441

Set textblock content to a string from settings

i have 2 textblocks in my form. something like this:

<TextBlock Name="applicationname" Text="{binding applicationname?}"/>
<TextBlock Name="applicationname" Text="{binding settings.stringVersionNumber}"/>

i would like to set the first textblock content to display the application name automatically and the other one to display a string saved in the application setting ..

should i be changing the values using a "wpf code-behind" or could i just bind the textblocks directly in the xaml ?

Upvotes: 2

Views: 1696

Answers (1)

Douglas
Douglas

Reputation: 54897

You can data bind to static properties, including the application settings, directly in XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:l="clr-namespace:WpfApplication1"
        xmlns:p="clr-namespace:WpfApplication1.Properties"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>
            <TextBlock Text="{Binding Source={x:Static l:MainWindow.AssemblyTitle}}"/>
            <TextBlock Text="{Binding Source={x:Static p:Settings.Default}, Path=VersionNumber}"/>
        </StackPanel>
    </Grid>
</Window>

…where WpfApplication1 is your namespace, and VersionNumber is a string defined in the application settings.

To get the assembly title, we’ll need some code-behind in the MainWindow class:

public static string AssemblyTitle
{
    get 
    {
        return Assembly.GetExecutingAssembly()
                       .GetCustomAttributes(typeof(AssemblyTitleAttribute), false)
                       .Cast<AssemblyTitleAttribute>()
                       .Select(a => a.Title)
                       .FirstOrDefault();
    }
}

P.S. You can’t assign the same name to two elements.

Upvotes: 5

Related Questions