我正在尝试为自定义的textBox实现ViewModel,这是我第一次尝试以this tutorial的方式执行ViewModel。
它是一个文件浏览器应用程序,只需要一个string address;
(不是集合),它包含自定义TextBox“ExploreAddress”的地址。
这个自定义TextBox有文本和图像(当前的图标)目录,它不是静态的)
public class ExploreAddressVM : INotifyPropertyChanged
{
private string _text;
private System.Windows.Media.ImageSource _image;
public string Text
{
get { return _text; }
set { _text = value; }
}
public System.Windows.Media.ImageSource Image
{
get { return _image; }
set { _image = value; }
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
XAML:
<UserControl.DataContext>
<l:ExploreAddressViewModel/>
</UserControl.DataContext>
<TextBox x:Name="txtAddress" Margin="34,5,32,0" TextWrapping="Wrap"
Text="{Binding Name}" Height="25"
VerticalAlignment="Top" FontWeight="Bold" MinHeight="25" MaxHeight="25">
<TextBox.Background>
<ImageBrush ImageSource="{Binding Image}" Stretch="None"/>
</TextBox.Background>
</TextBox>
这是将ViewModel与自定义TextBox
绑定的理想解决方案代码背后:
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
exploreAddress = (ExploreAddressViewModel)base.DataContext;
exploreAddress.Text = "My Computer";
}
private void GoButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(txtAddress.Text);
}
答案 0 :(得分:2)
我实际上不确定为什么我需要创建一个类 ExploreAddress,也许我可以把它放在同一个地方 ExploreAddressViewModel类
你不需要。
你有重复的内容,只需删除该类。
此外,您的属性设置者必须提升PropertyChanged
事件,如下所示:
public class ExploreAddressViewModel : INotifyPropertyChanged
{
private string _name
public string Name
{
get { return _name; }
set
{
_name = value;
RaisePropertyChanged("Name");
}
}
private ImageSource _image;
public ImageSource Image
{
get { return _image; }
set
{
_image = value;
RaisePropertyChanged("Image");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}