我正在學習WPF中與DataContext的系結方式,但我不能理解為什么會這樣運行。 下面是這些代碼。
Ex1:可以得到正確的系結資料(在后面的代碼中分配DataContext)
Xaml
<Window x:Class="DemoDataContextAndItemSource.MainWindow"/span>
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"/span>
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"/span>
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"/span>
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"/span>
xmlns:local="clr-namespace:DemoDataContextAndItemSource"
mc:Ignorable="d"/span>
Title="主視窗" Height="450" Width="800">
<StackPanel Margin="15">
<WrapPanel>
<TextBlock Text="視窗標題。 " />
<TextBox Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}" Width="150" />
</WrapPanel>
<WrapPanel Margin="0,10,0,0">
<TextBlock Text="視窗尺寸。" />
<TextBox Text="{Binding Width}" Width="50" />
<TextBlock Text=" x" />
<TextBox Text="{Binding Height}" Width="50" />
</WrapPanel>
</StackPanel>
</Window>
cs
public partial class MainWindow : Windowpublic MainWindow()
{
InitializeComponent()。
DataContext = this。
}
}
而Ex2:為什么寬度和高度的數字是NaN & 編譯失敗?(在Xaml中使用DataContext)
<Window x:Class="DemoDataContextAndItemSource.MainWindow"/span>
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"/span>
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"/span>
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"/span>
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"/span>
xmlns:local="clr-namespace:DemoDataContextAndItemSource"
mc:Ignorable="d"/span>
Title="MainWindow"/span> Height="450"/span> Width="800"/span>>
<Window.DataContext>
<local:MainWindow/>
</Window.DataContext>
<StackPanel Margin="15"/span>>
<WrapPanel>
<TextBlock Text="視窗標題。 " />
<TextBox Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}" Width="150" />
</WrapPanel>
<WrapPanel Margin="0,10,0,0">
<TextBlock Text="視窗尺寸。" />
<TextBox Text="{Binding Width}" Width="50" />
<TextBlock Text=" x" />
<TextBox Text="{Binding Height}" Width="50" />
</WrapPanel>
</StackPanel>
</Window>
uj5u.com熱心網友回復:
運算式
<Window.DataContext>
<local:MainWindow/>
</Window.DataContext>
將創建一個新的MainWindow實體并將其分配給DataContext屬性。
為了分配當前的實體,你將不得不寫
為了分配當前的實體,你將不得不寫
<Window ... DataContext="{Binding RelativeSource={RelativeSource Self}}"/span>>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/306648.html
標籤:
