我的表单中有 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/