WPF绑定不能在自定义UserControl上工作
问题描述:
我一直在为此挣扎三天,我觉得我非常接近解决方案,但我无法实现。WPF绑定不能在自定义UserControl上工作
我正在做一个数独谜题,我想创建一个自定义控件来显示九个3x3网格之一,所以我dan显示九个,并有一个很好的9x9网格。
我发现至少有30个不同的页面可以解释如何创建这个页面,但我找不到每个页面上的解决方案。
我认为问题出现在PartialSudokuGrid
中,因为Values
属性似乎没有被调用。另外,输出窗口中不显示错误。谁能告诉我我做错了什么?
没有意义转储代码,并期望有人解决它,但我真的坚持这一点,我觉得好像它只是一个小小的变化,将使一切工作。
这里是我的代码:
主窗口:
<Window x:Class="SudokuWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SudokuWPF"
Title="MainWindow" Height="400" Width="400"
DataContext="{Binding PartialSudokuGrid, Source={StaticResource Locator}}">
<UniformGrid Columns="3" Rows="3">
<local:PartialSudokuGrid Values="{Binding ValuesVM}" />
</UniformGrid>
</Window>
视图模型:
public class PartialSudokuGridVM : ViewModelBase {
private int[] _values;
public PartialSudokuGridVM() {
this.ValuesVM = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
}
public int[] ValuesVM {
get {
return this._values;
}
set {
this._values = value;
this.RaisePropertyChanged();
}
}
}
用户控件:
<UserControl x:Class="SudokuWPF.PartialSudokuGrid"
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="300" d:DesignWidth="300"
DataContext="{Binding RelativeSource={RelativeSource Self}, Path=Values}">
<UniformGrid>
<TextBox Text="{Binding [0]}" />
<TextBox Text="{Binding [1]}" />
<TextBox Text="{Binding [2]}" />
<TextBox Text="{Binding [3]}" />
<TextBox Text="{Binding [4]}" />
<TextBox Text="{Binding [5]}" />
<TextBox Text="{Binding [6]}" />
<TextBox Text="{Binding [7]}" />
<TextBox Text="{Binding [8]}" />
</UniformGrid>
</UserControl>
后面的代码:
public partial class PartialSudokuGrid : UserControl {
public PartialSudokuGrid() {
InitializeComponent();
}
public int[] Values {
get {
return (int[])GetValue(ValuesProperty);
}
set {
SetValue(ValuesProperty, value);
}
}
public static DependencyProperty ValuesProperty = DependencyProperty.Register("Values", typeof(int[]), typeof(PartialSudokuGrid));
}
修复:
像MDoobie建议,我删除了Self
从PartialGridView结合和清除代码隐藏文件(没有用了)。
老:
<local:PartialSudokuGrid Values="{Binding ValuesVM}" />
新:
<local:PartialSudokuGrid DataContext="{Binding ValuesVM}" />
答
我想你设置窗口的DataContext这条线DataContext="{Binding PartialSudokuGrid, Source={StaticResource Locator}}"
它被设置在PartialSudokuGrid不是PartialSudokuGridVM(具有ValuesVM属性)。尝试将PartialSudokuGridVm设置为DataContext。
这工作,谢谢!我认为绑定填充了PartialSudokuGrid中的属性,但没有。真棒!我将编辑我的答案以显示修复程序。 – Gideon 2014-12-13 15:20:17
我很高兴我帮你。 – MDoobie 2014-12-13 15:22:09