【发布时间】:2013-12-05 15:25:09
【问题描述】:
我想将两个图像外包给一个自定义用户控件,该控件应该设置两个属性,一个用于每个图像的来源。
但是我遇到了无法正确识别的数据上下文问题。这也可能是一个问题,这是我第一次使用依赖属性。无论如何,我希望你能弄清楚我的想法并在这里帮助我,源代码来了:
主视图模型:
public class MainWindowViewModel : INotifyPropertyChanged
{
private string _spielerL1;
private string _spielerL2;
public MainWindowViewModel()
{
SpielerL1 = System.IO.Directory.GetCurrentDirectory() + @"\Images\queen_of_clubs.png";
SpielerL2 = System.IO.Directory.GetCurrentDirectory() + @"\Images\queen_of_diamonds.png";
[...]
}
public string SpielerL1
{
get { return _spielerL1; }
private set
{
_spielerL1 = value;
OnPropertyChanged("SpielerL1");
}
}
public string SpielerL2
{
get { return _spielerL2; }
private set
{
_spielerL2 = value;
OnPropertyChanged("SpielerL2");
}
}
}
在我的主窗口视图中,我只实例化视图模型并使用带有 SourceLeft="{Binding SpielerL1}" 和 SourceRight="{Binding SpielerL2}" 的控件...
我的控制代码如下所示(删除了源代码以使其更短):
public partial class HandControl
{
public HandControl()
{
InitializeComponent();
DataContext = this;
}
public string SourceLeft
{
get
{
return (string) GetValue(SourceLeftProperty);
}
set
{
SetValue(SourceLeftProperty, value);
}
}
public static readonly DependencyProperty SourceLeftProperty = DependencyProperty.Register("SourceLeft", typeof(string), typeof(HandControl), new PropertyMetadata(""));
}
最后是我的用户控件 xaml,它无法识别数据上下文或至少不显示我的图像:
<UserControl x:Class="FoolMe.Gui.Controls.HandControl"
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">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<Image Grid.Column="1"
Source="{Binding SourceLeft}" />
<Image Grid.Row="0"
Grid.Column="0"
Grid.ColumnSpan="2"
Source="{Binding SourceRight}" />
</Grid>
</UserControl>
由于我还没有对 WPF 和用户控件做太多事情,所以我不知道有什么问题。没有用户控件它可以正常工作,但是像这样外包它,我的窗口保持“白色”。
有人知道,出了什么问题?
【问题讨论】:
-
无关:使用Path.Combine 组合路径部分。
-
还是谢谢你,随时欢迎建议:)
标签: c# wpf user-controls