【发布时间】:2011-05-23 07:51:55
【问题描述】:
我在 Silverlight 样式中遇到了绑定问题。
这是我的视图模型:
public class MyObject
{
public Uri TheUrl { get; set; }
public string MyText { get; set; }
}
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public MyObject Object1 { get { return new MyObject { TheUrl = new Uri("test.png", UriKind.Relative), MyText = "Test1" }; } }
public MyObject Object2 { get { return new MyObject { TheUrl = new Uri("test.png", UriKind.Relative), MyText = "Test2" }; } }
}
这是我的 xaml:
<UserControl.Resources>
<Style x:Key="TestStyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<StackPanel>
<TextBlock Text="{Binding MyObject.MyText}" />
<Image Source="{Binding MyObject.TheUrl}" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<UserControl.DataContext>
<vm:ViewModel />
</UserControl.DataContext>
<StackPanel x:Name="LayoutRoot" Background="White">
<Button Style="{StaticResource TestStyle}" Width="100" Height="100" Tag="{Binding Object1}" />
<Button Style="{StaticResource TestStyle}" Width="100" Height="100" Tag="{Binding Object2}" />
</StackPanel>
我以自己的风格测试了很多东西,但无法使绑定工作。
有人有想法吗?
提前感谢您的帮助 最好的问候。
编辑:
对视图模型的更改:
public class MyObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
private Uri _TheUrl;
public Uri TheUrl
{
get { return _TheUrl; }
set
{
_TheUrl = value;
NotifyPropertyChanged("TheUrl");
}
}
private string _MyText;
public string MyText
{
get { return _MyText; }
set
{
_MyText = value;
NotifyPropertyChanged("MyText");
}
}
}
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
private MyObject _Object1;
public MyObject Object1
{
get { return _Object1; }
set
{
_Object1 = value;
NotifyPropertyChanged("Object1");
}
}
private MyObject _Object2;
public MyObject Object2
{
get { return _Object2; }
set
{
_Object2 = value;
NotifyPropertyChanged("Object2");
}
}
public ViewModel()
{
Object1 = new MyObject {TheUrl = new Uri("test.png", UriKind.Relative), MyText = "Test1"};
Object2 = new MyObject { TheUrl = new Uri("test.png", UriKind.Relative), MyText = "Test2" };
}
}
【问题讨论】:
标签: silverlight binding styles