绑定到用户控件的依赖属性

时间:2018-04-25 07:02:58

标签: c# wpf user-controls dependency-properties

我有以下(简单)UserControl

XAML:

<UserControl x:Class="WpfUserControls.Controls.TextBlockUC"
             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" 
             xmlns:local="clr-WpfUserControls.Controls"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300"
             Name="TextBlockUserControl">
    <UserControl.Resources>
        <ResourceDictionary Source="../Resources/ResourceDictionary.xaml"/>
    </UserControl.Resources>
    <Grid>
        <TextBlock Text="{Binding ElementName=TextBlockUserControl, Path=Label}" Visibility="{Binding ElementName=TextBlockUserControl, Path=Visible, Converter={StaticResource BoolToVis}}"/>
    </Grid>
</UserControl>

代码背后:

using System.Windows;
using System.Windows.Controls;

namespace WpfUserControls.Controls
{
    public partial class TextBlockUC : UserControl
    {
        public TextBlockUC()
        {
            InitializeComponent();
            DataContext = this;
        }

        public string Label
        {
            get { return (string)GetValue(LabelProperty); }
            set { SetValue(LabelProperty, value); }
        }

        public static readonly DependencyProperty LabelProperty =
            DependencyProperty.Register("Label", typeof(string), typeof(TextBlockUC), new PropertyMetadata(""));

        public bool Visible
        {
            get { return (bool)GetValue(VisibleProperty); }
            set { SetValue(VisibleProperty, value); }
        }

        public static readonly DependencyProperty VisibleProperty =
            DependencyProperty.Register("Visible", typeof(bool), typeof(TextBlockUC), new PropertyMetadata(true));
    }
}

现在我想做以下

<uc:TextBlockUC Grid.Row="2" Grid.Column="8" Label="{Binding Test}" Visible="{Binding TransportersOnly}"></uc:ToolboxButtonUC>

其中<uc:>是对WpfUserControls命名空间的引用(显然),TestTransportersOnly是我的ViewModel中的属性。

为什么这不起作用的任何想法?

0 个答案:

没有答案