Wpf 如何将数据从C#传递到xaml?
我有这个xaml代码,需要从C代码中动态设置点Wpf 如何将数据从C#传递到xaml?,wpf,xaml,c#-4.0,Wpf,Xaml,C# 4.0,我有这个xaml代码,需要从C代码中动态设置点 MVVM解决方案: XAML文件: <Window x:Class="PolygonBinding.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWind
MVVM解决方案:
XAML文件:
<Window x:Class="PolygonBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style x:Key="Mystyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Polygon Points="{TemplateBinding Tag}" Fill="{TemplateBinding Background}"
Stroke="{TemplateBinding BorderBrush}"/>
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Button Style="{StaticResource Mystyle}" Tag="{Binding PointsSource}" />
</Grid>
</Window>
ViewModel文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Prism.ViewModel;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Media;
namespace PolygonBinding
{
class MainViewModel : NotificationObject
{
public MainViewModel()
{
PointsSource.Add(new Point { X = 0, Y =0 });
PointsSource.Add(new Point { X = 0, Y = 100 });
PointsSource.Add(new Point { X = 50, Y = 200 });
}
private PointCollection _pointsSource = new PointCollection();
public PointCollection PointsSource
{
get { return _pointsSource; }
set { _pointsSource = value; RaisePropertyChanged(() => PointsSource); }
}
}
}
嗯。使用ViewModel进行数据绑定@Moataz A.Mohammed发生了什么事?我的解决方案不起作用了?是的,我不知道为什么我现在正在尝试使用XamlReader。因为windows phone中的NotificationObject类不在普通WPF中dllsNotificationObject在Microsoft.Practices.Prism.dll程序集中,并且您可以在普通WPF应用程序中使用此类,而不仅仅是在windows phone中。另一方面,您可以实现interfejs INotifyPropertyChanged,一切都会正常。我使用这个类是因为它是更快的解决方案。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Prism.ViewModel;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Media;
namespace PolygonBinding
{
class MainViewModel : NotificationObject
{
public MainViewModel()
{
PointsSource.Add(new Point { X = 0, Y =0 });
PointsSource.Add(new Point { X = 0, Y = 100 });
PointsSource.Add(new Point { X = 50, Y = 200 });
}
private PointCollection _pointsSource = new PointCollection();
public PointCollection PointsSource
{
get { return _pointsSource; }
set { _pointsSource = value; RaisePropertyChanged(() => PointsSource); }
}
}
}