簡體   English   中英

通過數據綁定將值傳遞給WPF / C#代碼隱藏

[英]Pass Value through Data Binding to Code-Behind WPF/C#

我目前正在開發國際象棋游戲,並且正在嘗試將C#代碼背后的代碼連接到XAML中的WPF接口。 為了代表國際象棋棋盤,我創建了一個8x8的統一網格。 我想將正方形的名稱(網格的單元格)傳遞給后面的代碼,然后有一個方法返回相應塊的圖像的路徑。 例如,如果正方形a8上有一個白色的白鴉,它將被保存在后面的代碼中。 在xaml中,每個方塊都會傳遞其名稱(例如'a8'),並接收到指向白車圖像的路徑。 如果廣場上沒有一塊,則路徑將鏈接到透明圖像。 到目前為止,這是我得到的:

<StackPanel Height="auto" Width="auto" Orientation="Vertical" Margin="-5,0,5,0" >
    <UniformGrid  Rows="8" Columns="8" Background="Black" Height="800" Width="800"  HorizontalAlignment="Stretch">
        <StackPanel Orientation="Vertical" Margin="1,1,1,1">
            <Image Source="Resources/WhiteSquare.png"/>
            <Image Source=""/>
            <!--{Bind path to method in code-behind; pass name (e.g. a8); function then returns path to appropriate image of piece-->
        </StackPanel>
    </UniformGrid>
</StackPanel>

我會為我的xaml和c#帶來一些啟發。 謝謝!

您可能應該研究MVVM設計模式: https : //msdn.microsoft.com/zh-cn/library/hh848246.aspx 在構建基於XAML的UI應用程序時建議使用設計模式。

但是,要將在XAML標記中定義的元素的名稱傳遞給背后的代碼,可以處理該元素的Loaded事件。 例如,您可以將ImageTag屬性設置為“ a8”,並在類似以下代碼的代碼中處理handle是Loaded事件:

<UniformGrid  Rows="8" Columns="8" Background="Black" Height="800" Width="800"  HorizontalAlignment="Stretch">
    <StackPanel Orientation="Vertical" Margin="1,1,1,1">
        <Image Source="Resources/WhiteSquare.png"/>
        <Image Tag="a8" Loaded="Img_Loaded" />
    </StackPanel>
</UniformGrid>

private void Img_Loaded(object sender, RoutedEventArgs e)
{
    Image img = sender as Image;
    string name = img.Tag.ToString();

    //set source of Image based on the value of name here...
    //see for an example http://stackoverflow.com/questions/350027/setting-wpf-image-source-in-code
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM