如何在运行时动态应用wpf数据绑定



我一直在做WPF GUI在运行时生成的赋值。运行时生成的GUI由另一个wpf应用程序使用。模板生成器应用程序允许使用XAMLWriter创建GUI并将其保存为xml(xaml实际上是xml)。消费者应用程序使用XAMLReader在GUI上添加模板。现在我想要在生成的模板中的控件之间进行某种绑定。

要求:第一个日期选择器的日期=2015/01/02,文本框文本=1,则第二个日期选择器上的日期必须为2015/01/03。如果文本框text=-1,则第二个日期选择器上的日期必须为2015/01/01。

我是如何在运行时实现这一点的。由于生成的模板是从另一个应用程序生成的,因此无需硬编码。我们在控件的Tag属性上有一些特定的值,它指示我们涉及哪三个控件,哪个日期选择器是源,哪个日期拾取器是目标,以及需要使用哪个文本框文本。

是否可以使用动态数据绑定?或者如何实现

=>将Xml文件重命名为Xaml

<UserControl ...>
<Grid>
    <StackPanel Background="Aqua">
    <TextBlock Text="{Binding Path=Label}" Width="200" Height="40"/>
    </StackPanel>
</Grid>

=>如果有,这是您将与后面的代码合并的类

public class XamlLoadedType:UserControl, IComponentConnector
{
    private bool _contentLoaded; 
    public void InitializeComponent() {
        if (_contentLoaded) {
            return;
        }
        _contentLoaded = true;
        var resourceLocater = new System.Uri(_uri, System.UriKind.Relative);            
        Application.LoadComponent(this, resourceLocater);
    }
    void IComponentConnector.Connect(int connectionId, object target) {
        this._contentLoaded = true;
    }
    string _uri ;
    public XamlLoadedType(string uri)
    {
        _uri = uri;
        InitializeComponent();
    }   
}

=>主窗口及其视图模型:

<Window ...>
<Grid>
    <StackPanel>
        <Button Command="{Binding LoadCommand}" Width="100" Height="50">Load</Button>
    </StackPanel>
    <StackPanel Grid.Row="1">
        <ContentControl Content="{Binding LoadedContent}"/>
    </StackPanel>
</Grid>

public class MainViewModel:INotifyPropertyChanged
{
    public ICommand LoadCommand { get; set; }
    object _loadedContent;
    public object LoadedContent
    {
        get { return _loadedContent; }
        set {
            SetField(ref _loadedContent, value, "LoadedContent");
        }
    }
    public MainViewModel()
    {
        LoadCommand = new RelayCommand(Load, ()=>true);
    }
    private void Load()
    {
        var xamlLoaded = new XamlLoadedType("/WPFApplication1;component/XamlToLoad.xml.xaml");
        xamlLoaded.DataContext = new { Label = "HeyDude" };
        LoadedContent = xamlLoaded;
    }
}

Voilà

最新更新