Wpf 一次定义源并多次使用

Wpf 一次定义源并多次使用,wpf,xaml,Wpf,Xaml,目前,我正在使用以下代码将文本块绑定到应用程序设置 <Grid DataSource="{Binding DataContext.CurrentPatient, RelativeSource={RelativeSource AncestorType={x:Type Page}}"> ... ... ... <TextBlock Text="{Binding Source={StaticResource Settings}, Path=Default.Te

目前,我正在使用以下代码将
文本块
绑定到
应用程序设置

<Grid DataSource="{Binding DataContext.CurrentPatient, RelativeSource={RelativeSource AncestorType={x:Type Page}}">
   ...
   ...
   ...
   <TextBlock Text="{Binding Source={StaticResource Settings}, Path=Default.Test}" />
   <TextBox Text="{Binding Source={StaticResource Settings}, Path=Default.CurrentValue}" />
   <TextBlock Text="{Binding Source={StaticResource Settings}, Path=Default.NormalValue}" />
   ...
   ...
   ...
</Grid>

...
...
...
...
...
...
现在我不想在所有文本块中键入
Source={StaticResource Settings}

简而言之,我希望代码缩小。我的意思是我希望我的代码是可维护的,并且可以简化。

试试这个

public class Mybinding : Binding
{
    //Load only once and use every time :)
    static object Settings = App.Current.Resources["Settings"];

    public Mybinding()
    {
        Source = Settings; 
    }
}

 <TextBlock Text="{local:Mybinding Path=Default.Test}" />
公共类Mybinding:绑定
{
//仅加载一次,每次使用:)
静态对象设置=App.Current.Resources[“设置”];
公共Mybinding()
{
来源=设置;
}
}
>编辑

<Application.Resources>
  <ResourceDictionary>
     <properties:Settings x:Key="Settings" />
  </ResourceDictionary>
 </Application.Resources>


local是Mybinding的命名空间。我还没有测试过它。但希望这能给你一个想法。我希望“设置”在App.xaml中,或者在合并到App.xaml的ResourceDictionary中

<Grid DataContext={Binding Source={StaticResource Settings}}>
   <TextBlock Text="{Binding Default.Test}" />
   <TextBox Text="{Binding Default.CurrentValue}" />
   <TextBlock Text="{Binding Default.NormalValue}" />
<Grid>


我认为您的代码会运行良好。我试试看。但是它会降低性能吗?我问这个问题是因为我的应用程序中有1500多个属性需要绑定。请将其保存在某个全局类的某个静态变量中,并在加载App.xaml后在Begging中填充一次,然后从那里使用它。是的,如果有1500个属性,则每次都会在资源字典中查找该属性,从而降低性能。你知道吗可以将属性类型作为设置类型。但我确信对象类型也可以工作,因为绑定使用ReflectionTank。我将按照您的建议使用它。很抱歉,我没有提到您的假设,即“设置”在App.xaml或ResourceDictionary中与App.xaml合并。我正在努力学习教程。在那里,他使用了
x:key=“Settings”
,但当我尝试做同样的事情时,我得到一个错误,即“key”属性只能用于IDictionary中包含的元素。