I'm having a problem when dynamically adding a DataTrigger to an existing element.
在向現有元素動態添加DataTrigger時遇到問題。
If I hard-code it in MainWindow.XAML like this it works fine:
如果我在MainWindow.XAML中對它進行硬編碼,那么它可以正常工作:
In App.Xaml:
在App.Xaml中:
...
<Application.Resources>
<ControlTemplate x:Key="MyTemplate">
<TextBox AcceptsReturn="True" AcceptsTab="True" AllowDrop="True" Text="{Binding Content}"/>
</ControlTemplate>
</Application.Resources>
...
In MainWindow.XAML:
在MainWindow.XAML中:
...
<DataTemplate>
<Control x:Name="ViewPlaceHolder" Template="{StaticResource ViewPlaceHolderTemplate}" />
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding TypeName}" Value="MyViewModelName">
<Setter TargetName="ViewPlaceHolder" Property="Template" Value="{StaticResource MyTemplate}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
...
But if I create the DataTrigger in code behind as follows:
但是如果我在后面的代碼中創建DataTrigger如下:
...
DataTrigger tr = new DataTrigger();
Binding b = new Binding();
b.Path = new PropertyPath("TypeName");
tr.Value = triggerValue;
tr.Binding = b;
Setter st = new Setter(Control.TemplateProperty, "{StaticResource MyTemplate}");
st.TargetName = "ViewPlaceHolder";
tr.Setters.Add(st);
myDataTemplate.Triggers.Add(tr);
...
I get the following error during binding (there is no error when I add the trigger to the template and using XamlWriter.Write(myDataTemplate) shows its been added to the DataTemplate properly):
我在綁定期間遇到以下錯誤(當我將觸發器添加到模板並使用XamlWriter.Write(myDataTemplate)顯示它已正確添加到DataTemplate時沒有錯誤):
'StaticResource MyTemplate' is not a valid value for the 'System.Windows.Controls.Control.Template' property on a Setter.
'StaticResource MyTemplate'不是Setter上'System.Windows.Controls.Control.Template'屬性的有效值。
I have to load the Trigger at runtime because it (triggerValue) comes from an dynamically loaded plugin. If I add the ControlTemplate directly to the Setter instead of referencing it as a StaticResource it also works fine but I don't like the idea of having to load the same ControlTemplate on every page/window where I might need it.
我必須在運行時加載Trigger,因為它(triggerValue)來自動態加載的插件。如果我將ControlTemplate直接添加到Setter而不是將其作為StaticResource引用它也可以正常工作,但我不喜歡必須在我可能需要它的每個頁面/窗口上加載相同的ControlTemplate。
Any idea of how I can get the Setter in the DataTrigger to reference the resource if I add it from Code behind?
如果我從Code后面添加它,我怎么能在DataTrigger中獲取Setter來引用資源?
2
You are trying to set the value of the Template property to the actual literal string "{StaticResource MyTemplate}".
您正在嘗試將Template屬性的值設置為實際的文字字符串“{StaticResource MyTemplate}”。
You need to look up the resource instance using something like this:
您需要使用以下內容查找資源實例:
var myTemplate = Application.Current.TryFindResource("MyTemplate") as ControlTemplate;
// Do something appropriate if myTemplate is null
Setter st = new Setter(Control.TemplateProperty, myTemplate);
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/06/24/7209bd644cece0dd81f5b4a637e0f60b.html。