WPF 因設置不期望的DataContext,導致的綁定異常

来源:https://www.cnblogs.com/kybs0/archive/2019/12/03/11977281.html
-Advertisement-
Play Games

在MainWindow中,創建一個背景屬性BrushTest,並將其綁定至界面上UserControl的BackgroundTest屬性 UserControl,同樣添加一個BackgroundTest屬性,並將其綁定至界面。 運行後,控制台輸出綁定異常,背景設置並沒有生效。 System.Wind ...


在MainWindow中,創建一個背景屬性BrushTest,並將其綁定至界面上UserControl的BackgroundTest屬性

 1 <Window x:Class="WpfApp8.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 5         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 6         xmlns:local="clr-namespace:WpfApp8"
 7         mc:Ignorable="d"
 8         Title="MainWindow" Height="450" Width="800" x:Name="TheMainWindow">
 9     <Grid>
10         <local:UserControl1 BackgroundTest="{Binding BrushTest}"/>
11     </Grid>
12 </Window>
 1     public partial class MainWindow : Window
 2     {
 3         public MainWindow()
 4         {
 5             InitializeComponent();
 6             BrushTest = Brushes.Red;
 7             this.DataContext = this;
 8         }
10         public static readonly DependencyProperty BrushTestProperty = DependencyProperty.Register(
11             "BrushTest", typeof(SolidColorBrush), typeof(MainWindow), new PropertyMetadata(default(SolidColorBrush)));
13         public SolidColorBrush BrushTest
14         {
15             get { return (SolidColorBrush) GetValue(BrushTestProperty); }
16             set { SetValue(BrushTestProperty, value); }
17         }
18     }

UserControl,同樣添加一個BackgroundTest屬性,並將其綁定至界面。

 1 <UserControl x:Class="WpfApp8.UserControl1"
 2              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
 5              xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
 6              xmlns:local="clr-namespace:WpfApp8"
 7              mc:Ignorable="d" 
 8              d:DesignHeight="450" d:DesignWidth="800">
 9     <Grid Background="{Binding BackgroundTest}">
10     </Grid>
11 </UserControl>
 1     public partial class UserControl1 : UserControl
 2     {
 3         public UserControl1()
 4         {
 5             InitializeComponent();
 6             this.DataContext = this;
 7         }
 8         public static readonly DependencyProperty BackgroundTestProperty = DependencyProperty.Register(
 9             "BackgroundTest", typeof(SolidColorBrush), typeof(UserControl1), new PropertyMetadata(default(SolidColorBrush)));
10         public SolidColorBrush BackgroundTest
11         {
12             get { return (SolidColorBrush) GetValue(BackgroundTestProperty); }
13             set { SetValue(BackgroundTestProperty, value); }
14         }
15     }

運行後,控制台輸出綁定異常,背景設置並沒有生效。

System.Windows.Data Error: 40 : BindingExpression path error: 'BrushTest' property not found on 'object' ''UserControl1' (Name='')'.

BindingExpression:Path=BrushTest; DataItem='UserControl1' (Name=''); target element is 'UserControl1' (Name=''); target property is 'BackgroundTest' (type 'SolidColorBrush')

為何錯了?

因為UserControl設置了倆次DataContext,UserControl1內部設置的上下文覆蓋了主視窗設置的上下文。

視窗內<local:UserControl1 BackgroundTest="{Binding BrushTest}"/>綁定的值BrushTest,在UserControl下的上下文無法找到相關值,所以報錯了

 

此類綁定異常,一不小心還是很容易出現的。

在視窗設置了DataContext時(自身或者ViewModel),子控制項也設置DataContext。有趣的是,在Xaml編輯時,使用Reshaper鏈接到的是視窗所在的上下文屬性。

所以,子控制項設置DataContext時,需要關註下否有屬性被引用綁定外界數據。

建議子控制項減少DataContext的使用,以上可以通過指定數據源進行綁定。比如:

 1 <UserControl x:Class="WpfApp8.UserControl1"
 2              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
 5              xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
 6              xmlns:local="clr-namespace:WpfApp8"
 7              mc:Ignorable="d" 
 8              d:DesignHeight="450" d:DesignWidth="800" x:Name="TheUserControl">
 9     <Grid Background="{Binding ElementName=TheUserControl,Path=BackgroundTest}">
10     </Grid>
11 </UserControl>

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • .Net Core組件化視圖(部分視圖) 1.背景 1.以前我們使用.Net的時候使用部分視圖的方式在,.Net Core 中已經沒有了但是我們還是想使用現在的.Net Core換了一種方式,將視圖組件化了。 2.視圖組件介紹 1.可以將我們的視圖重覆的部分分離出來,達到可復用。 2.可以編寫業務邏 ...
  • 認證與授權一直以來都是很多人在討論的話題,之所以想這次談一談認證和授權,主要是因為最近看到許多文章都把認證和授權混為一談,把認證方式當作是授權方式。所以想寫篇文章談談我眼中的認證與授權 ...
  • IEnumerable是可枚舉的所有非泛型集合的基介面, IEnumerable包含一個方法GetEnumerator(),該方法返回一個IEnumerator;IEnumerator提供通過Current屬性以及MoveNext()和Reset()方法來迴圈訪問集合的功能。 ...
  • 一個簡單、基於AbpInterceptor的攔截器示例: 攔截器調用順序,可參考打上斷點調試分析: AutofacRegistration.Populate(內部調用Autofac.Extras.DynamicProxy) SimpleAsyncInterceptor.Intercept Castl ...
  • 在較早期的報表套打的時候,我傾向於使用LODOP的ActiveX進行報表的列印或者套打,BS效果還是很不錯的。之前利用它在Winform程式裡面實現信封套打功能,詳細參考《基於信封套打以及批量列印的實現過程》,雖然功能能夠完美實現,不過由於還需要附帶一個不是百分百整合一起的插件,還是有點另類的,雖然... ...
  • 在.NET Core中想給API進行安全認證,最簡單的無非就是Jwt,悠然記得一年前寫的Jwt Demo,現在拿回來改成.NET Core的,但是在編碼上的改變並不大,因為Jwt已經足夠強大了。在項目中分為 DotNetCore_Jwt_Server 以及 DotNetCore_Jwt_Client ...
  • 原文:http://www.zilaohu.cn/Jie/Detail_Jie?ID=78840a04-55b8-4988-80b2-f964fd822d63 下麵配置後:被拒絕的域請求後,可以進入方法,在瀏覽器接收響應的時候被當作是拒絕的。主要步驟:1.ConfigureServices()註冊c ...
  • 一、前言 由於公司要求項目需要走CI構建平臺,拋棄掉之前的人工編譯打包方式,所以需要調研一下項目怎麼通過命令行編譯出產物。 二、準備工作 1. 在構建機器上安裝vs(本文示例為vs2017) 2. 將代碼上傳版本控制倉庫(本文示例為Gitlab),並確保構建機器可以正常訪問並下載源代碼 3. 確保構 ...
一周排行
    -Advertisement-
    Play Games
  • 1. 說明 /* Performs operations on System.String instances that contain file or directory path information. These operations are performed in a cross-pla ...
  • 視頻地址:【WebApi+Vue3從0到1搭建《許可權管理系統》系列視頻:搭建JWT系統鑒權-嗶哩嗶哩】 https://b23.tv/R6cOcDO qq群:801913255 一、在appsettings.json中設置鑒權屬性 /*jwt鑒權*/ "JwtSetting": { "Issuer" ...
  • 引言 集成測試可在包含應用支持基礎結構(如資料庫、文件系統和網路)的級別上確保應用組件功能正常。 ASP.NET Core 通過將單元測試框架與測試 Web 主機和記憶體中測試伺服器結合使用來支持集成測試。 簡介 集成測試與單元測試相比,能夠在更廣泛的級別上評估應用的組件,確認多個組件一起工作以生成預 ...
  • 在.NET Emit編程中,我們探討了運算操作指令的重要性和應用。這些指令包括各種數學運算、位操作和比較操作,能夠在動態生成的代碼中實現對數據的處理和操作。通過這些指令,開發人員可以靈活地進行算術運算、邏輯運算和比較操作,從而實現各種複雜的演算法和邏輯......本篇之後,將進入第七部分:實戰項目 ...
  • 前言 多表頭表格是一個常見的業務需求,然而WPF中卻沒有預設實現這個功能,得益於WPF強大的控制項模板設計,我們可以通過修改控制項模板的方式自己實現它。 一、需求分析 下圖為一個典型的統計表格,統計1-12月的數據。 此時我們有一個需求,需要將月份按季度劃分,以便能夠直觀地看到季度統計數據,以下為該需求 ...
  • 如何將 ASP.NET Core MVC 項目的視圖分離到另一個項目 在當下這個年代 SPA 已是主流,人們早已忘記了 MVC 以及 Razor 的故事。但是在某些場景下 SSR 還是有意想不到效果。比如某些靜態頁面,比如追求首屏載入速度的時候。最近在項目中回歸傳統效果還是不錯。 有的時候我們希望將 ...
  • System.AggregateException: 發生一個或多個錯誤。 > Microsoft.WebTools.Shared.Exceptions.WebToolsException: 生成失敗。檢查輸出視窗瞭解更多詳細信息。 內部異常堆棧跟蹤的結尾 > (內部異常 #0) Microsoft ...
  • 引言 在上一章節我們實戰了在Asp.Net Core中的項目實戰,這一章節講解一下如何測試Asp.Net Core的中間件。 TestServer 還記得我們在集成測試中提供的TestServer嗎? TestServer 是由 Microsoft.AspNetCore.TestHost 包提供的。 ...
  • 在發現結果為真的WHEN子句時,CASE表達式的真假值判斷會終止,剩餘的WHEN子句會被忽略: CASE WHEN col_1 IN ('a', 'b') THEN '第一' WHEN col_1 IN ('a') THEN '第二' ELSE '其他' END 註意: 統一各分支返回的數據類型. ...
  • 在C#編程世界中,語法的精妙之處往往體現在那些看似微小卻極具影響力的符號與結構之中。其中,“_ =” 這一組合突然出現還真不知道什麼意思。本文將深入剖析“_ =” 的含義、工作原理及其在實際編程中的廣泛應用,揭示其作為C#語法奇兵的重要角色。 一、下劃線 _:神秘的棄元符號 下劃線 _ 在C#中並非 ...