我定义了用户控件来表示选项卡项的内容,以便将大型 XAML 文件拆分为较小的文件。我想将对数据对象的引用从主 UI 类传递给用户控件。
我知道 DependancyProperties 和 RelativeSource 是实现这一目标的方法,但由于我缺乏 WPF 专业知识,我不确定如何实现这一目标。有人能帮我吗。
谢谢
我有三个 xaml 文件,MainWindow、AlsTabUC (UserControl) 和 RangingTabUC (UserControl)。我有一个对象代表一个执行范围和环境光测量的设备,并且希望在单独的选项卡中执行这些活动。
对象 m_mySensorDevice 是 MainWindow 的成员,它是父窗口,我想将此对象传递给两个孩子,以便他们可以执行 readAmbientLight 和 readRange 方法。
当然,我提供了非常基本的示例代码来进行说明。实际上,这些选项卡包含更多信息(以及其他选项卡),因此是用户控件的原因。
主窗口 - XAML
<Window.Resources>
<System:String x:Key="strTabHeaderRanging">Ranging</System:String>
<System:String x:Key="strTabHeaderALS">ALS</System:String>
</Window.Resources>
<Grid>
<TabControl Name="MainTab" TabStripPlacement="Top"
Margin="0,20,0,10"
SelectionChanged="mainTab_SelectionChanged" >
<TabItem Name="tabItemRanging"
Header="{Binding Source={StaticResource strTabHeaderRanging}}">
<Grid>
<my:rangingTabUC HorizontalAlignment="Center"
VerticalAlignment="Center"
x:Name="rangingTabUC1"/>
</Grid>
</TabItem>
<TabItem Name="tabItemAls"
Header="{Binding Source={StaticResource strTabHeaderALS}}">
<Grid>
<my:AlsTabUC HorizontalAlignment="Center"
VerticalAlignment="Center"
x:Name="alsTabUC1" />
</Grid>
</TabItem>
</TabControl>
</Grid>
</Window>
主窗口 - 代码
public partial class MainWindow : Window
{
SensorDevice m_mySensorDevice;
public MainWindow()
{
m_mySensorDevice = new SensorDevice();
InitializeComponent();
}
private void mainTab_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
}
public class SensorDevice
{
}
AlsTabUC - XAML
<UserControl x:Class="TabUserControls.AlsTabUC">
<Grid>
<Button Height="25" Width="100" Name="readAmbientLight"
HorizontalAlignment="Center" VerticalAlignment="Center"
Click="readAmbientLight_Click" Margin="2">
Read Amb Light
</Button>
</Grid>
</UserControl>
AlsTabUC - 代码
public partial class AlsTabUC : UserControl
{
public AlsTabUC()
{
InitializeComponent();
}
private void readAmbientLight_Click(object sender, RoutedEventArgs e)
{
m_mySensorDevice.readAmbientLight();
}
}
测距表UC-XAML
<UserControl x:Class="TabUserControls.rangingTabUC">
<Grid>
<Button Height="25" Width="100" Name="readRange"
HorizontalAlignment="Center" VerticalAlignment="Center"
Click="readRange_Click" Margin="2">
Read Range
</Button>
</Grid>
</UserControl>
测距表UC-代码
public partial class rangingTabUC : UserControl
{
public rangingTabUC()
{
InitializeComponent();
}
private void readRange_Click(object sender, RoutedEventArgs e)
{
m_mySensorDevice.readRange();
}
}