c# - 从设置中将文本 block 内容设置为字符串

标签 c# wpf xaml

我的表单中有 2 个文本 block 。 像这样的东西:

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

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

我应该使用“wpf 代码隐藏”更改值还是可以直接在 xaml 中绑定(bind)文本 block ?

最佳答案

您可以直接在 XAML 中将数据绑定(bind)到静态属性,包括应用程序设置:

<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>

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

要获取程序集标题,我们需要在 MainWindow 类中添加一些代码:

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

附注您不能为两个元素分配相同的名称。

关于c# - 从设置中将文本 block 内容设置为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8948535/

相关文章:

c# - 透视表头样式

c# - 列表中的 wpf 扩展器在检查时并不总是执行命令

wpf - 用于 WPF 的 Deepzoom

c# - 在 WCF 操作契约中传递原始变量。优点和缺点?

c# - 在获取父实体 EFCore 时加载子实体

c# - 在 C# 中运行时取消选中复选框时禁用文本框

WPF Material 设计 Snackbar 持续时间

wpf - DataGrid 中的文本对齐方式

c# - 从 JSONPath 构建 JObject

c# - WPF:如何只从文本框中获取时间?