C# WPF {x:Reference}的作用
{x:Reference} 是XAML中的一個(gè)標(biāo)記擴(kuò)展(Markup Extension),它的作用很簡(jiǎn)單但很重要:獲取對(duì)XAML中另一個(gè)命名元素的引用。
基本語(yǔ)法
{x:Reference 元素名稱(chēng)}
作用詳解
1. 在綁定中引用其他元素
這是最常見(jiàn)的用法,替代 ElementName:
<StackPanel>
<Slider x:Name="mySlider" Minimum="0" Maximum="100"/>
<TextBox Text="{Binding Path=Value, Source={x:Reference mySlider}}"/>
</StackPanel>
2. 在任何需要對(duì)象引用的地方使用
{x:Reference} 不限于綁定,可以在任何需要對(duì)象引用的屬性中使用:
<StackPanel>
<Button x:Name="btn1" Content="按鈕1"/>
<!-- 將btn2的CommandTarget設(shè)置為btn1 -->
<Button Content="按鈕2"
CommandTarget="{x:Reference btn1}"
Command="ApplicationCommands.Copy"/>
</StackPanel>
與 ElementName 的對(duì)比
使用 ElementName:
<TextBox Text="{Binding Value, ElementName=mySlider}"/>
使用 {x:Reference}:
<TextBox Text="{Binding Value, Source={x:Reference mySlider}}"/>
兩者效果相同,但 {x:Reference} 更靈活:
優(yōu)勢(shì)場(chǎng)景
1. 在非綁定場(chǎng)景中使用
<Grid>
<TextBlock x:Name="titleText" Text="標(biāo)題"/>
<!-- 將ToolTip的PlacementTarget設(shè)置為titleText -->
<Button Content="幫助"
ToolTip="{x:Reference titleText}"
ToolTipService.PlacementTarget="{x:Reference titleText}"/>
</Grid>
2. 在樣式中使用
<Style TargetType="TextBox">
<Setter Property="Text"
Value="{Binding Value, Source={x:Reference SomeSlider}}"/>
</Style>
3. 引用非直接相關(guān)的元素
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Slider x:Name="mainSlider" Grid.Row="0"/>
<StackPanel Grid.Row="1">
<!-- 引用不同面板中的元素 -->
<TextBox Text="{Binding Value, Source={x:Reference mainSlider}}"/>
</StackPanel>
</Grid>
注意事項(xiàng)
1. 引用必須在同一名稱(chēng)范圍內(nèi)
<!-- 這樣是OK的 -->
<Window>
<Slider x:Name="slider1"/>
<TextBox Source="{x:Reference slider1}"/>
</Window>
<!-- 這樣可能有問(wèn)題 -->
<Window>
<UserControl>
<Slider x:Name="slider1"/>
</UserControl>
<!-- 這里可能引用不到slider1,因?yàn)槊Q(chēng)范圍不同 -->
<TextBox Source="{x:Reference slider1}"/>
</Window>
2. 避免循環(huán)引用
<!-- 錯(cuò)誤:循環(huán)引用 -->
<TextBox x:Name="text1" Text="{Binding Text, Source={x:Reference text1}}"/>
總結(jié)
{x:Reference} 就是XAML中的"取地址符"或"引用符",它:
- 作用:按名稱(chēng)獲取XAML元素的引用
- 用途:在綁定、命令目標(biāo)、樣式等各種場(chǎng)景中引用其他元素
- 優(yōu)勢(shì):比
ElementName更靈活,可用于非綁定場(chǎng)景 - 限制:被引用的元素必須有
x:Name且在同一個(gè)名稱(chēng)范圍內(nèi)
理解 {x:Reference} 有助于你更深入地掌握XAML的引用機(jī)制!

浙公網(wǎng)安備 33010602011771號(hào)