[英]WPF user control bind data to user control property
我有用戶控制權:
XAML
<UserControl x:Class="controlmaker.checkButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="114" d:DesignWidth="221">
<Grid Background="Aqua" >
<CheckBox Content="CheckBox" Height="16" HorizontalAlignment="Left" Margin="58,24,0,0" Name="checkBox1" VerticalAlignment="Top" />
<Button Content="{Binding buttText}" Height="23" HorizontalAlignment="Left" Margin="58,57,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
</Grid>
</UserControl>
代碼背后
public partial class checkButton : UserControl
{
public checkButton()
{
InitializeComponent();
}
public static readonly DependencyProperty buttTextProperty =
DependencyProperty.Register("buttText", typeof(String),
typeof(checkButton), new FrameworkPropertyMetadata(string.Empty));
public String buttText
{
get { return GetValue(buttTextProperty).ToString(); }
set { SetValue(buttTextProperty, value); }
}
}
和主窗口xaml
<Window x:Class="controlmaker.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" xmlns:my="clr-namespace:controlmaker">
<Grid>
<my:checkButton buttText="aka" HorizontalAlignment="Left" Margin="145,115,0,0" x:Name="checkButton1" VerticalAlignment="Top" Height="133" Width="250" />
</Grid>
</Window>
我想在窗口xaml中綁定用戶控件屬性,並將其在用戶控件中綁定到按鈕內容屬性。 怎么做?
您可以在用戶控件中嘗試元素綁定。 只需為UserControl命名並綁定屬性:
<UserControl x:Class="controlmaker.checkButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="114" d:DesignWidth="221"
x:Name="MyUserControl">
<Grid Background="Aqua" >
<CheckBox Content="CheckBox" Height="16" HorizontalAlignment="Left"
Margin="58,24,0,0" Name="checkBox1" VerticalAlignment="Top" />
<Button Content="{Binding Path=buttText, ElementName=MyUserControl}"
Height="23" HorizontalAlignment="Left" Margin="58,57,0,0"
Name="button1" VerticalAlignment="Top" Width="75" />
</Grid>
</UserControl>
然后,您可以綁定或放置來自用戶控件使用位置的靜態文本
<my:checkButton buttText="aka" />
要么
<my:checkButton buttText="{Binding SomeProperty}" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.