0

これらの回答を確認しましたが、探している情報はありませんでした:
ツリービューのコードで WPF データテンプレートをセットアップする方法は?
コードでコントロール テンプレートを設定するには?
WPF で ControlTemplate をプログラムで作成する

ここに私のコードの要点があります:

DataGridTextColumn col = new DataGridTextColumn();
Style styl = null;
//        Need to add this on a per-column basis
// <common:RequiredPropertyDisplayBrushConverter x:Key="requiredDisplayBrushConverter" />  
string xaml = "<ControlTemplate TargetType=\"{x:Type DataGridCell}\"> <TextBox Background=\"{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Text, Converter={StaticResource requiredDisplayBrushConverter}  > </TextBox> </ControlTemplate>";
MemoryStream sr = new MemoryStream(Encoding.ASCII.GetBytes(xaml));
ParserContext pc = new ParserContext();
pc.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
pc.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
ControlTemplate  ct = (ControlTemplate)XamlReader.Load(sr, pc);

styl.Setters.Add(new Setter(TemplateProperty, ct));
col.CellStyle = styl;  

ControlTemplate では、バインドはコメントで言及されているコンバーターを参照します。コンバーターが xaml で DataGrid のリソースとして定義されている場合、実行時エラーが発生します: {"'requiredDisplayBrushConverter' という名前のリソースが見つかりません。リソース名は大文字と小文字を区別します。"
} または、実行時に DataGrid のリソースに追加しますか?
それとも何か他のテクニックがありますか?
ありがとう -

4

1 に答える 1

2

xaml に追加できますが、再配置する必要があります。リソースは、使用する前に定義する必要があります。つまり、背景を子タグとして定義する必要があります。

xaml を次のように変更します。

string xaml = "<ControlTemplate TargetType=\"{x:Type DataGridCell}\"><TextBox><TextBox.Resources><common:RequiredPropertyDisplayBrushConverter x:Key=\"requiredDisplayBrushConverter\" /></TextBox.Resources><TextBox.Background><Binding RelativeSource=\"{RelativeSource TemplatedParent}\" Path=\"Content.Text\" Converter=\"{StaticResource requiredDisplayBrushConverter}\"/></TextBox.Background></TextBox></ControlTemplate>";

そして、共通の名前空間を定義する必要があります。これを他の名前空間の後に追加します(もちろん、正しい名前空間/アセンブリを使用して):

pc.XmlnsDictionary.Add("common", "clr-namespace:WPFApplication;assembly=WPFApplication");

または、オプションである場合は、リソースを App.xaml に追加することもできます。

于 2016-01-27T18:31:48.650 に答える