これは主に好奇心からの質問であり、バインディング、XAML、および拡張構文をよりよく理解するのに役立つことを願っています。
したがって、バインディングソースをMainWindowからMainWindowでインスタンス化したオブジェクトに変更したいだけです。
これが私のC#コードです:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
favclass myfavclass = new favclass();
InitializeComponent();
this.DataContext = this;
}
string _myString = "hello";
public string MyString
{
get { return _myString; }
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(
this, new PropertyChangedEventArgs(propName));
}
}
public class favclass : INotifyPropertyChanged
{
int _myint = 34;
public int MyInt
{
get { return _myint; }
set { _myint = value; }
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(
this, new PropertyChangedEventArgs(propName));
}
}
}
と私のXAML
<Window x:Class="WpfApplication1.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" >
<Grid>
<TextBlock Height="50" Width="50" Text="{Binding MyString}"/>
<TextBlock Height="50" Width="48" Margin="200,100,100,100"
Text="{Binding Source=myfavclass, Path=MyInt}"/>
</Grid>
</Window>
ご覧のとおり、最初にメインウィンドウからMyStringプロパティを表示します。
次に、myfavclassオブジェクトからMyIntを表示します。しかしもちろん、MyIntは表示されません。考えられるすべてのバリエーションを試しました。
どのXAMLがありませんか?なぜ私が持っているXAMLが機能しないのですか?
ありがとう
Source=myfavclass
これは間違っています。Source
次のような要素構文を使用してのみ直接割り当てることができます。
<Binding>
<Binding.Source>
<!-- value here -->
</Binding.Source>
</Binding>
または、次のようなStaticResource
またはDynamicResoure
またはカスタムを使用できますMarkupExtension
。
Text="{Binding Source={StaticResource someKey}, Path=MyInt}"
または、新機能{x:Reference}
を使用して、XAML内の名前付き要素への直接参照を取得します。
Text="{Binding Source={x:Reference someName}, Path=MyInt}"
さらに、myfavclass
はコードビハインド内でローカル変数として宣言されています。XAMLコード内で使用(参照)できる方法はありません。
あなたは複数のビューモデルと呼ばれる何かをしています。その場合は、コントロールに複数のDataContextを提供する必要があります。ネストされたビューモデルを使用することを好みます。これを実装するには、次のMainWindow
ように変更してみてください。
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
_myfavclass = new favclass();
InitializeComponent();
this.DataContext = this;
}
private readonly favclass _myfavclass;
//we will use this property inside XAML code
public favclass MyFavClass {
get {
return _myfavclass;
}
}
}
今、XAMLコードでは、あなたがにテキストをバインドできるMyFavClass.MyInt
ことを、ノートDataContext
あなただけ指定する必要があるので、暗黙的に結合するためのソースですPath
。
<TextBlock Height="50" Width="48" Margin="200,100,100,100"
Text="{Binding Path=MyFavClass.MyInt}"/>
あなたMyInt
はを使用して適切に実装されていませんINotifyPropertyChanged
(しかし、あなたがすでにそれを知っていることを願っています)。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加