WPF用户控件将数据绑定到用户控件属性

WPF用户控件将数据绑定到用户控件属性,wpf,binding,user-controls,controls,Wpf,Binding,User Controls,Controls,我有用户控制: xaml 和主窗口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:

我有用户控制:

xaml

和主窗口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>


我想在windowxaml中绑定用户控件属性,并在用户控件中将其绑定到按钮内容属性。如何操作?

您可以尝试在用户控件内部进行元素绑定。只需为UserControl和bind属性指定一个名称:

<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" />



谁更感兴趣如何使它更正确,我高度推荐您如何指定什么类型的VM用户控件应该作为参考数据?想象一下,VM不在同一个命名空间中,ETC提问是——在自己的XAML中绑定用户控件属性,当前的示例不使用MVVM模式,如果您需要在用户控件中使用MVVM和绑定视图模型,那么您必须设置用户控件的DATACONTRONT来查看模型实例,或者如果需要类型重写,请考虑DataTemplate:
<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}" />