c# - 如何在运行时动态应用 wpf 数据绑定(bind)

标签 c# wpf xaml data-binding datepicker

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

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

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

是否可以使用动态数据绑定(bind)?或者如何实现这一点

最佳答案

=> 将您的 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();
    }   
}

=> 主窗口及其 View 模型:

<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;

    }
}

关于c# - 如何在运行时动态应用 wpf 数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29259631/

相关文章:

c# - 无法为 Rfc2898DeriveBytes 指定 4 个参数(哈希算法名称)

c# - RestSharp序列化JSON数组请求参数

c# - 完全关闭辅助窗口

c# - 获取 ListBoxItem 的索引 - WPF

c# - Silverlight 网格未填满整个空间

c# - 如何防止其他应用程序窃取焦点?

C# UserControl 多重继承

wpf - 在 WPF 中使用 slider 缩放图像时卡住

c# - 应用程序资源的数据绑定(bind)窗口标题

wpf - 将 VisualStateManager.VisualStateGroups 分离到资源字典