【发布时间】:2014-05-22 19:03:33
【问题描述】:
我正在创建将充当其他控件的容器的用户控件。我在 StackOverflow 上找到了代码,并使用该示例创建了用户控件。 这是我的用户控件的代码。
<UserControl x:Class="ClassLibrary1.UserControl1"
xmlns:local="clr-namespace:ClassLibrary1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<UserControl.Template>
<ControlTemplate>
<StackPanel>
<Button Content="Custom Control Text Area 1" IsEnabled="{Binding IsEnabled}" />
<ContentPresenter Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}"/>
<TextBlock Text="Custom Control Text Area 2" />
</StackPanel>
</ControlTemplate>
</UserControl.Template>
代码如下
namespace ClassLibrary1
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
}
}
}
然后我在其他 windows 应用程序项目中添加了这个用户控件,并在这个用户控件中添加了按钮,所以代码如下所示
<StackPanel>
<l:UserControl1>
<StackPanel >
<Button Click="Button_Click" Content="Click"/>
<Button Content="My Control's Content" IsEnabled="{Binding Isbuttonenable}"/>
</StackPanel>
</l:UserControl1>
</StackPanel>
现在我的 Windows 应用程序项目工作正常,按钮控件能够基于 Isbuttonenable valye 启用/禁用。
现在我更新了用户控件并将 ViewModel 添加到用户控件。这是用户控件代码背后的代码
namespace ClassLibrary1
{
public partial class UserControl1 : UserControl
{
UserControl1ViewModel model = new UserControl1ViewModel();
public UserControl1()
{
InitializeComponent();
this.DataContext = model;
}
}
}
现在,当我在我的 Windows 应用程序项目中使用此更新后的控件时,数据绑定不再起作用。按钮现在不再能够基于 Isbuttonenable 值启用/禁用。这可能是什么解决方案。我想将 ViewModel 保留在我的用户控件中。
我尝试了很多方法和护目镜,但无法找到解决方案。
【问题讨论】:
-
我尝试了很多方法,但没有任何效果。然后我找到解释:“TemplateBinding 不支持双向绑定,只有 Binding 支持。即使使用 BindsTwoWayBeDefault 选项,它也不支持双向绑定。”看到这个stackoverflow.com/questions/5913176/…
标签: wpf user-controls contentpresenter