从设置中将textblock内容设置为字符串

leb*_*ero 2 c# wpf xaml

我的表单中有2个文本块.这样的事情:

<TextBlock Name="applicationname" Text="{binding applicationname?}"/>
<TextBlock Name="applicationname" Text="{binding settings.stringVersionNumber}"/>
Run Code Online (Sandbox Code Playgroud)

我想设置第一个文本块内容自动显示应用程序名称,另一个显示保存在应用程序设置中的字符串.

我应该使用"wpf代码隐藏"来更改值,还是我可以直接在xaml中绑定文本块?

Dou*_*las 5

您可以直接在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>
Run Code Online (Sandbox Code Playgroud)

... WpfApplication1您的命名空间在哪里,VersionNumber是应用程序设置中定义的字符串.

要获得程序集标题,我们需要在MainWindow类中使用一些代码隐藏:

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

PS您不能为两个元素指定相同的名称.