数据绑定到我的用户控件的依赖项属性不起作用

时间:2015-10-29 16:16:46

标签: c# data-binding user-controls windows-runtime

我正在制作一个用户控件来表示所选的数字(比如抽奖)。问题是当在数据模板内绑定它时绑定不起作用。 在对值进行硬编码时,它的工作方式是正确的。

错误属于这种类型,它们出现在我绑定到

的每个依赖项属性中
Error: BindingExpression path error: 'BackCheckedColor' property not found on 'NumberControlTest.Controls.NumberControl'. BindingExpression: Path='BackCheckedColor' DataItem='NumberControlTest.Controls.NumberControl'; target element is 'NumberControlTest.Controls.NumberControl' (Name='null'); target property is 'CheckedBackgroundColor' (type 'String')

我觉得奇怪的是,这部分错误 BindingExpression: Path='BackCheckedColor' DataItem='NumberControlTest.Controls.NumberControl' 它表明它试图在usercontrol本身中找到BackCheckedColor。这对我来说没有意义。有人可以帮忙吗?

用户控制Xaml

<UserControl.Resources>        
    <local:CheckedToBrushConverter x:Key="CheckedToBrushConverter" 
                                   CheckedBackgroundColor="{Binding CheckedBackgroundColor}"
                                   CheckedForegroundColor="{Binding CheckedForegroundColor}"
                                   UncheckedBackgroundColor="{Binding UncheckedBackgroundColor}"
                                   UncheckedForegroundColor="{Binding UncheckedForegroundColor}"/>
</UserControl.Resources>
<Grid Tapped="Grid_Tapped">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="16*"/>
        <ColumnDefinition Width="130*"/>
        <ColumnDefinition Width="16*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="16*"/>
        <RowDefinition Height="130*"/>
        <RowDefinition Height="30*"/>
    </Grid.RowDefinitions>

    <Ellipse x:Name="Ellipse" Grid.RowSpan="3" Grid.ColumnSpan="3" Fill="{Binding IsChecked, Converter={StaticResource CheckedToBrushConverter}, ConverterParameter=background}"/>
    <Viewbox Grid.Row="1" Grid.Column="1">
        <TextBlock x:Name="NumberBlock" TextWrapping="Wrap" FontFamily="Segoe UI" Text="{Binding NumberValue}" Foreground="{Binding IsChecked, Converter={StaticResource CheckedToBrushConverter}, ConverterParameter=foreground}" />        
    </Viewbox>

</Grid>

背后的用户控制代码

 public sealed partial class NumberControl : UserControl
{
    public NumberControl()
    {
        this.InitializeComponent();
        this.DataContext = this;
    }

    public string UncheckedBackgroundColor
    {
        get { return (string)GetValue(UncheckedBackgroundColorProperty); }
        set { SetValue(UncheckedBackgroundColorProperty, value); }
    }

    // Using a DependencyProperty as the backing store for UncheckedBackgroundColor.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty UncheckedBackgroundColorProperty =
        DependencyProperty.Register("UncheckedBackgroundColor", typeof(string), typeof(NumberControl), new PropertyMetadata(string.Empty));


    public string CheckedBackgroundColor
    {
        get { return (string)GetValue(CheckedBackgroundColorProperty); }
        set { SetValue(CheckedBackgroundColorProperty, value); }
    }

    // Using a DependencyProperty as the backing store for CheckedBackgroundColor.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CheckedBackgroundColorProperty =
        DependencyProperty.Register("CheckedBackgroundColor", typeof(string), typeof(NumberControl), new PropertyMetadata(string.Empty));

加上更多的依赖属性。

MainPage xaml

<Page.Resources>
    <DataTemplate x:Key="NumberTemplate">
        <Grid>
            <controls:NumberControl 
                UncheckedBackgroundColor="{Binding BackUncheckedColor}"
                UncheckedForegroundColor="{Binding ForeUncheckedColor}"
                CheckedBackgroundColor="{Binding BackCheckedColor}"
                CheckedForegroundColor="{Binding ForeCheckedColor}"
                NumberValue="{Binding Value}" 
                IsChecked="{Binding IsChecked}"
                HorizontalAlignment="Center" 
                VerticalAlignment="Center" Width="45" Height="45"/>
        </Grid>
    </DataTemplate>
</Page.Resources>

<Grid Background="#0f455f">
    <GridView x:Name="NumbersGridView" ItemTemplate="{StaticResource NumberTemplate}" ItemsSource="{Binding Numbers, Mode=TwoWay}"/>
    <Button x:Name="printButton" Content="Print" VerticalAlignment="Bottom" HorizontalAlignment="Center" Click="printButton_Click"/>
</Grid>

模型类,它提供绑定到gridview的集合数据

public class MockNumber
{
    public MockNumber(bool isChecked, int value, string backchcolor, string forchcolor, string backunchcolor, string forunchcolor)
    {
        IsChecked = isChecked;
        Value = value;
        BackCheckedColor = backchcolor;
        ForeCheckedColor = forchcolor;
        BackUncheckedColor = backunchcolor;
        ForeUncheckedColor = forunchcolor;
    }

    public bool IsChecked { get; set; }
    public int Value { get; set; }
    public string BackCheckedColor { get; set; }
    public string ForeCheckedColor { get; set; }
    public string BackUncheckedColor { get; set; }
    public string ForeUncheckedColor { get; set; }
}

编辑:如何在MainPage代码隐藏中实例化和绑定模型。

public MainPage()
    {
        this.InitializeComponent();
        this.DataContext = this;
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        makelist();
    }

    void makelist()
    {
        for (int i = 1; i <= 20; i++)
        {
            Numbers.Add(new MockNumber(i % 4 == 0 ? true : false, i, "#dead2b", "#000000", "#dead2b", "#f0b60c"));
        }
    }

    private ObservableCollection<MockNumber> numbers = new ObservableCollection<MockNumber>();
    public ObservableCollection<MockNumber> Numbers
    {
        get
        {
            return numbers;
        }
        set
        {
            numbers = value;
        }
    }

1 个答案:

答案 0 :(得分:1)

它之所以试图找到&#39; BackCheckedColor&#39; NumberControl的属性是因为您将用户控件的datacontext设置为自身。

public NumberControl()
{
   this.InitializeComponent();
   this.DataContext = this;
}

您告诉用户控件您的数据上下文本身。这意味着当你做&#34; {Binding}&#34;路径应该是用户控件的属性,我认为这不是一个好主意。

我知道您想要将一些依赖项属性绑定到Model类,但我没有在您的示例中看到您实例化模型类并将其用作数据上下文。

要考虑的另一件事是,您可能希望使用自定义控件而不是用户控件。我可以看到您向用户控件添加了一些依赖项属性,但实际上,依赖项属性已添加到自定义控件和附加属性的静态类。

编辑: 在阅读了您的附加代码后,我可以看到用户控件的datacontext被设置为&#39;这个&#39;这本身就是。你需要删除它。

public sealed partial class NumberControl : UserControl
{
    public NumberControl()
    {
        this.InitializeComponent();
        this.DataContext = this; //Remove this line 
    }
//...

然后在删除之后,usercontrol应该继承GridViewItem的Binding,或者您可以显式地将datacontext放在DataTemplate中。

<DataTemplate x:Key="NumberTemplate">
    <Grid>
        <controls:NumberControl DataContext="{Binding}" <!--specify the data context-->
            UncheckedBackgroundColor="{Binding BackUncheckedColor}"
//..